<!DOCTYPE HTML>
<html lang="zh-CN">


<head>
    <meta charset="utf-8">
    <meta name="keywords" content="Android 扩展知识点, 天机阁">
    <meta name="description" content="
ART
ART 功能
预先 (AOT) 编译
垃圾回收优化
开发和调试方面的优化


ART GC


Apk 包体优化
Apk 组成结构
整体优化
资源优化
代码优化
.arsc文件优化
lib目录优化


Hook
基本流程
使用示例">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
    <meta name="renderer" content="webkit|ie-stand|ie-comp">
    <meta name="mobile-web-app-capable" content="yes">
    <meta name="format-detection" content="telephone=no">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
    <meta name="referrer" content="no-referrer-when-downgrade">
    <!-- Global site tag (gtag.js) - Google Analytics -->


    <title>Android 扩展知识点 | 天机阁</title>
    <link rel="icon" type="image/png" href="/hello-world/favicon.png">
    


    <!-- bg-cover style     -->



<link rel="stylesheet" type="text/css" href="/hello-world/libs/awesome/css/all.min.css">
<link rel="stylesheet" type="text/css" href="/hello-world/libs/materialize/materialize.min.css">
<link rel="stylesheet" type="text/css" href="/hello-world/libs/aos/aos.css">
<link rel="stylesheet" type="text/css" href="/hello-world/libs/animate/animate.min.css">
<link rel="stylesheet" type="text/css" href="/hello-world/libs/lightGallery/css/lightgallery.min.css">
<link rel="stylesheet" type="text/css" href="/hello-world/css/matery.css">
<link rel="stylesheet" type="text/css" href="/hello-world/css/my.css">
<link rel="stylesheet" type="text/css" href="/hello-world/css/dark.css" media="none" onload="if(media!='all')media='all'">




    <link rel="stylesheet" href="/hello-world/libs/tocbot/tocbot.css">
    <link rel="stylesheet" href="/hello-world/css/post.css">




    
        <link rel="stylesheet" type="text/css" href="/hello-world/css/reward.css">
    



    <script src="/hello-world/libs/jquery/jquery-3.6.0.min.js"></script>

<meta name="generator" content="Hexo 6.3.0"></head>


<body>
    <header class="navbar-fixed">
    <nav id="headNav" class="bg-color nav-transparent">
        <div id="navContainer" class="nav-wrapper container">
            <div class="brand-logo">
                <a href="/hello-world/" class="waves-effect waves-light">
                    
                    <img src="/hello-world/medias/logo.png" class="logo-img" alt="LOGO">
                    
                    <span class="logo-span">天机阁</span>
                </a>
            </div>
            

<a href="#" data-target="mobile-nav" class="sidenav-trigger button-collapse"><i class="fas fa-bars"></i></a>
<ul class="right nav-menu">
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/hello-world/" class="waves-effect waves-light">
      
      <i class="fas fa-home" style="zoom: 0.6;"></i>
      
      <span>首页</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/hello-world/tags" class="waves-effect waves-light">
      
      <i class="fas fa-tags" style="zoom: 0.6;"></i>
      
      <span>标签</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/hello-world/categories" class="waves-effect waves-light">
      
      <i class="fas fa-bookmark" style="zoom: 0.6;"></i>
      
      <span>分类</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/hello-world/archives" class="waves-effect waves-light">
      
      <i class="fas fa-archive" style="zoom: 0.6;"></i>
      
      <span>归档</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/hello-world/about" class="waves-effect waves-light">
      
      <i class="fas fa-user-circle" style="zoom: 0.6;"></i>
      
      <span>关于</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/hello-world/contact" class="waves-effect waves-light">
      
      <i class="fas fa-comments" style="zoom: 0.6;"></i>
      
      <span>留言板</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/hello-world/friends" class="waves-effect waves-light">
      
      <i class="fas fa-address-book" style="zoom: 0.6;"></i>
      
      <span>友情链接</span>
    </a>
    
  </li>
  
  <li>
    <a href="#searchModal" class="modal-trigger waves-effect waves-light">
      <i id="searchIcon" class="fas fa-search" title="搜索" style="zoom: 0.85;"></i>
    </a>
  </li>
  <li>
    <a href="javascript:;" class="waves-effect waves-light" onclick="switchNightMode()" title="深色/浅色模式" >
      <i id="sum-moon-icon" class="fas fa-sun" style="zoom: 0.85;"></i>
    </a>
  </li>
</ul>


<div id="mobile-nav" class="side-nav sidenav">

    <div class="mobile-head bg-color">
        
        <img src="/hello-world/medias/logo.png" class="logo-img circle responsive-img">
        
        <div class="logo-name">天机阁</div>
        <div class="logo-desc">
            
            或许不知是梦的缘故，流离之人总在追逐幻影
            
        </div>
    </div>

    <ul class="menu-list mobile-menu-list">
        
        <li class="m-nav-item">
	  
		<a href="/hello-world/" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-home"></i>
			
			首页
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/hello-world/tags" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-tags"></i>
			
			标签
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/hello-world/categories" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-bookmark"></i>
			
			分类
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/hello-world/archives" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-archive"></i>
			
			归档
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/hello-world/about" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-user-circle"></i>
			
			关于
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/hello-world/contact" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-comments"></i>
			
			留言板
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/hello-world/friends" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-address-book"></i>
			
			友情链接
		</a>
          
        </li>
        
        
        <li><div class="divider"></div></li>
        <li>
            <a href="https://github.com/blinkfox/hexo-theme-matery" class="waves-effect waves-light" target="_blank">
                <i class="fab fa-github-square fa-fw"></i>Fork Me
            </a>
        </li>
        
    </ul>
</div>


        </div>

        
            <style>
    .nav-transparent .github-corner {
        display: none !important;
    }

    .github-corner {
        position: absolute;
        z-index: 10;
        top: 0;
        right: 0;
        border: 0;
        transform: scale(1.1);
    }

    .github-corner svg {
        color: #0f9d58;
        fill: #fff;
        height: 64px;
        width: 64px;
    }

    .github-corner:hover .octo-arm {
        animation: a 0.56s ease-in-out;
    }

    .github-corner .octo-arm {
        animation: none;
    }

    @keyframes a {
        0%,
        to {
            transform: rotate(0);
        }
        20%,
        60% {
            transform: rotate(-25deg);
        }
        40%,
        80% {
            transform: rotate(10deg);
        }
    }
</style>

<a href="https://github.com/blinkfox/hexo-theme-matery" class="github-corner tooltipped hide-on-med-and-down" target="_blank"
   data-tooltip="Fork Me" data-position="left" data-delay="50">
    <svg viewBox="0 0 250 250" aria-hidden="true">
        <path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path>
        <path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2"
              fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path>
        <path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z"
              fill="currentColor" class="octo-body"></path>
    </svg>
</a>
        
    </nav>

</header>

    



<div class="bg-cover pd-header post-cover" style="background-image: url('/hello-world/medias/featureimages/11.jpg')">
    <div class="container" style="right: 0px;left: 0px;">
        <div class="row">
            <div class="col s12 m12 l12">
                <div class="brand">
                    <h1 class="description center-align post-title">Android 扩展知识点</h1>
                </div>
            </div>
        </div>
    </div>
</div>




<main class="post-container content">

    
    <div class="row">
    <div id="main-content" class="col s12 m12 l9">
        <!-- 文章内容详情 -->
<div id="artDetail">
    <div class="card">
        <div class="card-content article-info">
            <div class="row tag-cate">
                <div class="col s7">
                    
                    <div class="article-tag">
                        
                            <a href="/hello-world/tags/%E5%AD%A6%E4%B9%A0/">
                                <span class="chip bg-color">学习</span>
                            </a>
                        
                    </div>
                    
                </div>
                <div class="col s5 right-align">
                    
                </div>
            </div>

            <div class="post-info">
                
                <div class="post-date info-break-policy">
                    <i class="far fa-calendar-minus fa-fw"></i>发布日期:&nbsp;&nbsp;
                    2022-11-28
                </div>
                

                

                

                

                
            </div>
        </div>
        <hr class="clearfix">

        

        

        <div class="card-content article-card-content">
            <div id="articleContent">
                <ul>
<li><a href="#art">ART</a><ul>
<li><a href="#art-%E5%8A%9F%E8%83%BD">ART 功能</a><ul>
<li><a href="#%E9%A2%84%E5%85%88-aot-%E7%BC%96%E8%AF%91">预先 (AOT) 编译</a></li>
<li><a href="#%E5%9E%83%E5%9C%BE%E5%9B%9E%E6%94%B6%E4%BC%98%E5%8C%96">垃圾回收优化</a></li>
<li><a href="#%E5%BC%80%E5%8F%91%E5%92%8C%E8%B0%83%E8%AF%95%E6%96%B9%E9%9D%A2%E7%9A%84%E4%BC%98%E5%8C%96">开发和调试方面的优化</a></li>
</ul>
</li>
<li><a href="#art-gc">ART GC</a></li>
</ul>
</li>
<li><a href="#apk-%E5%8C%85%E4%BD%93%E4%BC%98%E5%8C%96">Apk 包体优化</a><ul>
<li><a href="#apk-%E7%BB%84%E6%88%90%E7%BB%93%E6%9E%84">Apk 组成结构</a></li>
<li><a href="#%E6%95%B4%E4%BD%93%E4%BC%98%E5%8C%96">整体优化</a></li>
<li><a href="#%E8%B5%84%E6%BA%90%E4%BC%98%E5%8C%96">资源优化</a></li>
<li><a href="#%E4%BB%A3%E7%A0%81%E4%BC%98%E5%8C%96">代码优化</a></li>
<li><a href="#arsc%E6%96%87%E4%BB%B6%E4%BC%98%E5%8C%96">.arsc文件优化</a></li>
<li><a href="#lib%E7%9B%AE%E5%BD%95%E4%BC%98%E5%8C%96">lib目录优化</a></li>
</ul>
</li>
<li><a href="#hook">Hook</a><ul>
<li><a href="#%E5%9F%BA%E6%9C%AC%E6%B5%81%E7%A8%8B">基本流程</a></li>
<li><a href="#%E4%BD%BF%E7%94%A8%E7%A4%BA%E4%BE%8B">使用示例</a></li>
</ul>
</li>
<li><a href="#proguard">Proguard</a><ul>
<li><a href="#%E8%A7%84%E5%88%99">规则</a></li>
<li><a href="#%E5%85%AC%E5%85%B1%E6%A8%A1%E6%9D%BF">公共模板</a></li>
<li><a href="#%E5%B8%B8%E7%94%A8%E7%9A%84%E8%87%AA%E5%AE%9A%E4%B9%89%E6%B7%B7%E6%B7%86%E8%A7%84%E5%88%99">常用的自定义混淆规则</a></li>
<li><a href="#aar%E4%B8%AD%E5%A2%9E%E5%8A%A0%E7%8B%AC%E7%AB%8B%E7%9A%84%E6%B7%B7%E6%B7%86%E9%85%8D%E7%BD%AE">aar中增加独立的混淆配置</a></li>
<li><a href="#%E6%A3%80%E6%9F%A5%E6%B7%B7%E6%B7%86%E5%92%8C%E8%BF%BD%E8%B8%AA%E5%BC%82%E5%B8%B8">检查混淆和追踪异常</a></li>
</ul>
</li>
<li><a href="#%E6%9E%B6%E6%9E%84">架构</a><ul>
<li><a href="#mvc">MVC</a></li>
<li><a href="#mvp">MVP</a></li>
<li><a href="#mvvm">MVVM</a></li>
</ul>
</li>
<li><a href="#jetpack">Jetpack</a><ul>
<li><a href="#%E6%9E%B6%E6%9E%84-1">架构</a></li>
<li><a href="#%E4%BD%BF%E7%94%A8%E7%A4%BA%E4%BE%8B-1">使用示例</a></li>
</ul>
</li>
<li><a href="#ndk-%E5%BC%80%E5%8F%91">NDK 开发</a><ul>
<li><a href="#jni-%E5%9F%BA%E7%A1%80">JNI 基础</a><ul>
<li><a href="#%E6%95%B0%E6%8D%AE%E7%B1%BB%E5%9E%8B">数据类型</a></li>
<li><a href="#string-%E5%AD%97%E7%AC%A6%E4%B8%B2%E5%87%BD%E6%95%B0%E6%93%8D%E4%BD%9C">String 字符串函数操作</a></li>
<li><a href="#%E5%B8%B8%E7%94%A8-jni-%E8%AE%BF%E9%97%AE-java-%E5%AF%B9%E8%B1%A1%E6%96%B9%E6%B3%95">常用 JNI 访问 Java 对象方法</a></li>
</ul>
</li>
<li><a href="#ndk-%E5%BC%80%E5%8F%91-1">NDK 开发</a><ul>
<li><a href="#%E5%9F%BA%E7%A1%80%E5%BC%80%E5%8F%91%E6%B5%81%E7%A8%8B">基础开发流程</a></li>
<li><a href="#systemloadlibrary">System.loadLibrary()</a></li>
</ul>
</li>
<li><a href="#cmake-%E6%9E%84%E5%BB%BA-ndk-%E9%A1%B9%E7%9B%AE">CMake 构建 NDK 项目</a></li>
<li><a href="#%E5%B8%B8%E7%94%A8%E7%9A%84-android-ndk-%E5%8E%9F%E7%94%9F-api">常用的 Android NDK 原生 API</a></li>
</ul>
</li>
<li><a href="#%E7%B1%BB%E5%8A%A0%E8%BD%BD%E5%99%A8">类加载器</a><ul>
<li><a href="#%E5%8F%8C%E4%BA%B2%E5%A7%94%E6%89%98%E6%A8%A1%E5%BC%8F">双亲委托模式</a></li>
<li><a href="#dexpathlist">DexPathList</a></li>
</ul>
</li>
</ul>
<h1 id="ART"><a href="#ART" class="headerlink" title="ART"></a>ART</h1><p>ART 代表 Android Runtime，其处理应用程序执行的方式完全不同于 Dalvik，Dalvik 是依靠一个 Just-In-Time (JIT) 编译器去解释字节码。开发者编译后的应用代码需要通过一个解释器在用户的设备上运行，这一机制并不高效，但让应用能更容易在不同硬件和架构上运 行。ART 则完全改变了这套做法，在应用安装时就预编译字节码到机器语言，这一机制叫 Ahead-Of-Time (AOT）编译。在移除解释代码这一过程后，应用程序执行将更有效率，启动更快。</p>
<h2 id="ART-功能"><a href="#ART-功能" class="headerlink" title="ART 功能"></a>ART 功能</h2><h3 id="预先-AOT-编译"><a href="#预先-AOT-编译" class="headerlink" title="预先 (AOT) 编译"></a>预先 (AOT) 编译</h3><p>ART 引入了预先编译机制，可提高应用的性能。ART 还具有比 Dalvik 更严格的安装时验证。在安装时，ART 使用设备自带的 dex2oat 工具来编译应用。该实用工具接受 DEX 文件作为输入，并为目标设备生成经过编译的应用可执行文件。该工具应能够顺利编译所有有效的 DEX 文件。</p>
<h3 id="垃圾回收优化"><a href="#垃圾回收优化" class="headerlink" title="垃圾回收优化"></a>垃圾回收优化</h3><p>垃圾回收 (GC) 可能有损于应用性能，从而导致显示不稳定、界面响应速度缓慢以及其他问题。ART 通过以下几种方式对垃圾回收做了优化：</p>
<ul>
<li>只有一次（而非两次）GC 暂停</li>
<li>在 GC 保持暂停状态期间并行处理</li>
<li>在清理最近分配的短时对象这种特殊情况中，回收器的总 GC 时间更短</li>
<li>优化了垃圾回收的工效，能够更加及时地进行并行垃圾回收，这使得 GC_FOR_ALLOC 事件在典型用例中极为罕见</li>
<li>压缩 GC 以减少后台内存使用和碎片</li>
</ul>
<h3 id="开发和调试方面的优化"><a href="#开发和调试方面的优化" class="headerlink" title="开发和调试方面的优化"></a>开发和调试方面的优化</h3><ul>
<li>支持采样分析器</li>
</ul>
<p>一直以来，开发者都使用 Traceview 工具（用于跟踪应用执行情况）作为分析器。虽然 Traceview 可提供有用的信息，但每次方法调用产生的开销会导致 Dalvik 分析结果出现偏差，而且使用该工具明显会影响运行时性能</p>
<p>ART 添加了对没有这些限制的专用采样分析器的支持，因而可更准确地了解应用执行情况，而不会明显减慢速度。KitKat 版本为 Dalvik 的 Traceview 添加了采样支持。</p>
<ul>
<li>支持更多调试功能</li>
</ul>
<p>ART 支持许多新的调试选项，特别是与监控和垃圾回收相关的功能。例如，查看堆栈跟踪中保留了哪些锁，然后跳转到持有锁的线程；询问指定类的当前活动的实例数、请求查看实例，以及查看使对象保持有效状态的参考；过滤特定实例的事件（如断点）等。</p>
<ul>
<li>优化了异常和崩溃报告中的诊断详细信息</li>
</ul>
<p>当发生运行时异常时，ART 会为您提供尽可能多的上下文和详细信息。ART 会提供 <code>java.lang.ClassCastException</code>、<code>java.lang.ClassNotFoundException</code> 和 <code>java.lang.NullPointerException</code> 的更多异常详细信息（较高版本的 Dalvik 会提供 <code>java.lang.ArrayIndexOutOfBoundsException</code> 和 <code>java.lang.ArrayStoreException</code> 的更多异常详细信息，这些信息现在包括数组大小和越界偏移量；ART 也提供这类信息）。</p>
<h2 id="ART-GC"><a href="#ART-GC" class="headerlink" title="ART GC"></a>ART GC</h2><p>ART 有多个不同的 GC 方案，这些方案包括运行不同垃圾回收器。默认方案是 CMS（并发标记清除）方案，主要使用粘性 CMS 和部分 CMS。粘性 CMS 是 ART 的不移动分代垃圾回收器。它仅扫描堆中自上次 GC 后修改的部分，并且只能回收自上次 GC 后分配的对象。除 CMS 方案外，当应用将进程状态更改为察觉不到卡顿的进程状态（例如，后台或缓存）时，ART 将执行堆压缩。</p>
<p>除了新的垃圾回收器之外，ART 还引入了一种基于位图的新内存分配程序，称为 RosAlloc（插槽运行分配器）。此新分配器具有分片锁，当分配规模较小时可添加线程的本地缓冲区，因而性能优于 DlMalloc。</p>
<p>与 Dalvik 相比，ART CMS 垃圾回收计划在很多方面都有一定的改善：</p>
<ul>
<li><p>与 Dalvik 相比，暂停次数从 2 次减少到 1 次。Dalvik 的第一次暂停主要是为了进行根标记，即在 ART 中进行并发标记，让线程标记自己的根，然后马上恢复运行。</p>
</li>
<li><p>与 Dalvik 类似，ART GC 在清除过程开始之前也会暂停 1 次。两者在这方面的主要差异在于：在此暂停期间，某些 Dalvik 环节在 ART 中并发进行。这些环节包括 java.lang.ref.Reference 处理、系统弱清除（例如，jni 弱全局等）、重新标记非线程根和卡片预清理。在 ART 暂停期间仍进行的阶段包括扫描脏卡片以及重新标记线程根，这些操作有助于缩短暂停时间。</p>
</li>
<li><p>相对于 Dalvik，ART GC 改进的最后一个方面是粘性 CMS 回收器增加了 GC 吞吐量。不同于普通的分代 GC，粘性 CMS 不移动。系统会将年轻对象保存在一个分配堆栈（基本上是 java.lang.Object 数组）中，而非为其设置一个专属区域。这样可以避免移动所需的对象以维持低暂停次数，但缺点是容易在堆栈中加入大量复杂对象图像而使堆栈变长。</p>
</li>
</ul>
<p>ART GC 与 Dalvik 的另一个主要区别在于 ART GC 引入了移动垃圾回收器。使用移动 GC 的目的在于通过堆压缩来减少后台应用使用的内存。目前，触发堆压缩的事件是 ActivityManager 进程状态的改变。当应用转到后台运行时，它会通知 ART 已进入不再“感知”卡顿的进程状态。此时 ART 会进行一些操作（例如，压缩和监视器压缩），从而导致应用线程长时间暂停。目前正在使用的两个移动 GC 是同构空间压缩和半空间压缩。</p>
<ul>
<li><p>半空间压缩将对象在两个紧密排列的碰撞指针空间之间进行移动。这种移动 GC 适用于小内存设备，因为它可以比同构空间压缩稍微多节省一点内存。额外节省出的空间主要来自紧密排列的对象，这样可以避免 RosAlloc&#x2F;DlMalloc 分配器占用开销。由于 CMS 仍在前台使用，且不能从碰撞指针空间中进行收集，因此当应用在前台使用时，半空间还要再进行一次转换。这种情况并不理想，因为它可能引起较长时间的暂停。</p>
</li>
<li><p>同构空间压缩通过将对象从一个 RosAlloc 空间复制到另一个 RosAlloc 空间来实现。这有助于通过减少堆碎片来减少内存使用量。这是目前非低内存设备的默认压缩模式。相比半空间压缩，同构空间压缩的主要优势在于应用从后台切换到前台时无需进行堆转换。</p>
</li>
</ul>
<h1 id="Apk-包体优化"><a href="#Apk-包体优化" class="headerlink" title="Apk 包体优化"></a>Apk 包体优化</h1><h2 id="Apk-组成结构"><a href="#Apk-组成结构" class="headerlink" title="Apk 组成结构"></a>Apk 组成结构</h2><table>
<thead>
<tr>
<th>文件&#x2F;文件夹</th>
<th>作用&#x2F;功能</th>
</tr>
</thead>
<tbody><tr>
<td>res</td>
<td>包含所有没有被编译到 .arsc 里面的资源文件</td>
</tr>
<tr>
<td>lib</td>
<td>引用库的文件夹</td>
</tr>
<tr>
<td>assets</td>
<td>assets文件夹相比于 res 文件夹，还有可能放字体文件、预置数据和web页面等,通过 AssetManager 访问</td>
</tr>
<tr>
<td>META_INF</td>
<td>存放的是签名信息，用来保证 apk 包的完整性和系统的安全。在生成一个APK的时候，会对所有的打包文件做一个校验计算，并把结果放在该目录下面</td>
</tr>
<tr>
<td>classes.dex</td>
<td>包含编译后的应用程序源码转化成的dex字节码。APK 里面，可能会存在多个 dex 文件</td>
</tr>
<tr>
<td>resources.arsc</td>
<td>一些资源和标识符被编译和写入这个文件</td>
</tr>
<tr>
<td>Androidmanifest.xml</td>
<td>编译时，应用程序的 AndroidManifest.xml 被转化成二进制格式</td>
</tr>
</tbody></table>
<h2 id="整体优化"><a href="#整体优化" class="headerlink" title="整体优化"></a>整体优化</h2><ul>
<li>分离应用的独立模块，以插件的形式加载</li>
<li>解压APK，重新用 7zip 进行压缩</li>
<li>用 apksigner 签名工具 替代 java 提供的 jarsigner 签名工具</li>
</ul>
<h2 id="资源优化"><a href="#资源优化" class="headerlink" title="资源优化"></a>资源优化</h2><ul>
<li>可以只用一套资源图片，一般采用 xhdpi 下的资源图片</li>
<li>通过扫描文件的 MD5 值，找出名字不同，内容相同的图片并删除</li>
<li>通过 Lint 工具扫描工程资源，移除无用资源</li>
<li>通过 Gradle 参数配置 shrinkResources&#x3D;true</li>
<li>对 png 图片压缩</li>
<li>图片资源考虑采用 WebP 格式</li>
<li>避免使用帧动画，可使用 Lottie 动画库</li>
<li>优先考虑能否用 shape 代码、.9 图、svg 矢量图、VectorDrawable 类来替换传统的图片</li>
</ul>
<h2 id="代码优化"><a href="#代码优化" class="headerlink" title="代码优化"></a>代码优化</h2><ul>
<li>启用混淆以移除无用代码</li>
<li>剔除 R 文件</li>
<li>用注解替代枚举</li>
</ul>
<h2 id="arsc文件优化"><a href="#arsc文件优化" class="headerlink" title=".arsc文件优化"></a>.arsc文件优化</h2><ul>
<li>移除未使用的备用资源来优化 .arsc 文件<figure class="highlight groovy"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">android &#123;</span><br><span class="line">    defaultConfig &#123;</span><br><span class="line">        ...</span><br><span class="line">        resConfigs <span class="string">&quot;zh&quot;</span>, <span class="string">&quot;zh_CN&quot;</span>, <span class="string">&quot;zh_HK&quot;</span>, <span class="string">&quot;en&quot;</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></li>
</ul>
<h2 id="lib目录优化"><a href="#lib目录优化" class="headerlink" title="lib目录优化"></a>lib目录优化</h2><ul>
<li>只提供对主流架构的支持，比如 arm，对于 mips 和 x86 架构可以考虑不提供支持<figure class="highlight groovy"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">android &#123;</span><br><span class="line">    defaultConfig &#123;</span><br><span class="line">        ...</span><br><span class="line">        ndk &#123;</span><br><span class="line">            abiFilters  <span class="string">&quot;armeabi-v7a&quot;</span></span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></li>
</ul>
<h1 id="Hook"><a href="#Hook" class="headerlink" title="Hook"></a>Hook</h1><h2 id="基本流程"><a href="#基本流程" class="headerlink" title="基本流程"></a>基本流程</h2><p>1、根据需求确定 要 hook 的对象<br>2、寻找要hook的对象的持有者，拿到要 hook 的对象<br>3、定义“要 hook 的对象”的代理类，并且创建该类的对象<br>4、使用上一步创建出来的对象，替换掉要 hook 的对象</p>
<h2 id="使用示例"><a href="#使用示例" class="headerlink" title="使用示例"></a>使用示例</h2><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment">* hook的核心代码</span></span><br><span class="line"><span class="comment">* 这个方法的唯一目的：用自己的点击事件，替换掉 View 原来的点击事件</span></span><br><span class="line"><span class="comment">*</span></span><br><span class="line"><span class="comment">* <span class="doctag">@param</span> view hook的范围仅限于这个view</span></span><br><span class="line"><span class="comment">*/</span></span><br><span class="line"><span class="meta">@SuppressLint(&#123;&quot;DiscouragedPrivateApi&quot;, &quot;PrivateApi&quot;&#125;)</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">hook</span><span class="params">(Context context, <span class="keyword">final</span> View view)</span> &#123;<span class="comment">//</span></span><br><span class="line">    <span class="keyword">try</span> &#123;</span><br><span class="line">        <span class="comment">// 反射执行View类的getListenerInfo()方法，拿到v的mListenerInfo对象，这个对象就是点击事件的持有者</span></span><br><span class="line">        <span class="type">Method</span> <span class="variable">method</span> <span class="operator">=</span> View.class.getDeclaredMethod(<span class="string">&quot;getListenerInfo&quot;</span>);</span><br><span class="line">        method.setAccessible(<span class="literal">true</span>);<span class="comment">//由于getListenerInfo()方法并不是public的，所以要加这个代码来保证访问权限</span></span><br><span class="line">        <span class="type">Object</span> <span class="variable">mListenerInfo</span> <span class="operator">=</span> method.invoke(view);<span class="comment">//这里拿到的就是mListenerInfo对象，也就是点击事件的持有者</span></span><br><span class="line"></span><br><span class="line">        <span class="comment">// 要从这里面拿到当前的点击事件对象</span></span><br><span class="line">        Class&lt;?&gt; listenerInfoClz = Class.forName(<span class="string">&quot;android.view.View$ListenerInfo&quot;</span>);<span class="comment">// 这是内部类的表示方法</span></span><br><span class="line">        <span class="type">Field</span> <span class="variable">field</span> <span class="operator">=</span> listenerInfoClz.getDeclaredField(<span class="string">&quot;mOnClickListener&quot;</span>);</span><br><span class="line">        <span class="keyword">final</span> View.<span class="type">OnClickListener</span> <span class="variable">onClickListenerInstance</span> <span class="operator">=</span> (View.OnClickListener) field.get(mListenerInfo);<span class="comment">//取得真实的mOnClickListener对象</span></span><br><span class="line"></span><br><span class="line">        <span class="comment">// 2. 创建我们自己的点击事件代理类</span></span><br><span class="line">        <span class="comment">//   方式1：自己创建代理类</span></span><br><span class="line">        <span class="comment">//   ProxyOnClickListener proxyOnClickListener = new ProxyOnClickListener(onClickListenerInstance);</span></span><br><span class="line">        <span class="comment">//   方式2：由于View.OnClickListener是一个接口，所以可以直接用动态代理模式</span></span><br><span class="line">        <span class="comment">// Proxy.newProxyInstance的3个参数依次分别是：</span></span><br><span class="line">        <span class="comment">// 本地的类加载器;</span></span><br><span class="line">        <span class="comment">// 代理类的对象所继承的接口（用Class数组表示，支持多个接口）</span></span><br><span class="line">        <span class="comment">// 代理类的实际逻辑，封装在new出来的InvocationHandler内</span></span><br><span class="line">        <span class="type">Object</span> <span class="variable">proxyOnClickListener</span> <span class="operator">=</span> Proxy.newProxyInstance(context.getClass().getClassLoader(), <span class="keyword">new</span> <span class="title class_">Class</span>[]&#123;View.OnClickListener.class&#125;, <span class="keyword">new</span> <span class="title class_">InvocationHandler</span>() &#123;</span><br><span class="line">            <span class="meta">@Override</span></span><br><span class="line">            <span class="keyword">public</span> Object <span class="title function_">invoke</span><span class="params">(Object proxy, Method method, Object[] args)</span> <span class="keyword">throws</span> Throwable &#123;</span><br><span class="line">                Log.d(<span class="string">&quot;HookSetOnClickListener&quot;</span>, <span class="string">&quot;点击事件被hook到了&quot;</span>);<span class="comment">//加入自己的逻辑</span></span><br><span class="line">                <span class="keyword">return</span> method.invoke(onClickListenerInstance, args);<span class="comment">//执行被代理的对象的逻辑</span></span><br><span class="line">            &#125;</span><br><span class="line">        &#125;);</span><br><span class="line">        <span class="comment">// 3. 用我们自己的点击事件代理类，设置到&quot;持有者&quot;中</span></span><br><span class="line">        field.set(mListenerInfo, proxyOnClickListener);</span><br><span class="line">    &#125; <span class="keyword">catch</span> (Exception e) &#123;</span><br><span class="line">        e.printStackTrace();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 自定义代理类</span></span><br><span class="line"><span class="keyword">static</span> <span class="keyword">class</span> <span class="title class_">ProxyOnClickListener</span> <span class="keyword">implements</span> <span class="title class_">View</span>.OnClickListener &#123;</span><br><span class="line">    View.OnClickListener oriLis;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="title function_">ProxyOnClickListener</span><span class="params">(View.OnClickListener oriLis)</span> &#123;</span><br><span class="line">        <span class="built_in">this</span>.oriLis = oriLis;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">onClick</span><span class="params">(View v)</span> &#123;</span><br><span class="line">        Log.d(<span class="string">&quot;HookSetOnClickListener&quot;</span>, <span class="string">&quot;点击事件被hook到了&quot;</span>);</span><br><span class="line">        <span class="keyword">if</span> (oriLis != <span class="literal">null</span>) &#123;</span><br><span class="line">            oriLis.onClick(v);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h1 id="Proguard"><a href="#Proguard" class="headerlink" title="Proguard"></a>Proguard</h1><p>Proguard 具有以下三个功能：</p>
<ul>
<li>压缩（Shrink）: 检测和删除没有使用的类，字段，方法和特性</li>
<li>优化（Optimize） : 分析和优化Java字节码</li>
<li>混淆（Obfuscate）: 使用简短的无意义的名称，对类，字段和方法进行重命名</li>
</ul>
<h2 id="规则"><a href="#规则" class="headerlink" title="规则"></a>规则</h2><ul>
<li>关键字</li>
</ul>
<table>
<thead>
<tr>
<th>关键字</th>
<th>描述</th>
</tr>
</thead>
<tbody><tr>
<td>keep</td>
<td>保留类和类中的成员，防止被混淆或移除</td>
</tr>
<tr>
<td>keepnames</td>
<td>保留类和类中的成员，防止被混淆，成员没有被引用会被移除</td>
</tr>
<tr>
<td>keepclassmembers</td>
<td>只保留类中的成员，防止被混淆或移除</td>
</tr>
<tr>
<td>keepclassmembernames</td>
<td>只保留类中的成员，防止被混淆，成员没有引用会被移除</td>
</tr>
<tr>
<td>keepclasseswithmembers</td>
<td>保留类和类中的成员，防止被混淆或移除，保留指明的成员</td>
</tr>
<tr>
<td>keepclasseswithmembernames</td>
<td>保留类和类中的成员，防止被混淆，保留指明的成员，成员没有引用会被移除</td>
</tr>
</tbody></table>
<ul>
<li>通配符</li>
</ul>
<table>
<thead>
<tr>
<th>通配符</th>
<th>描述</th>
</tr>
</thead>
<tbody><tr>
<td>&lt;field&gt;</td>
<td>匹配类中的所有字段</td>
</tr>
<tr>
<td>&lt;method&gt;</td>
<td>匹配类中所有的方法</td>
</tr>
<tr>
<td>&lt;init&gt;</td>
<td>匹配类中所有的构造函数</td>
</tr>
<tr>
<td>*</td>
<td>匹配任意长度字符，不包含包名分隔符(.)</td>
</tr>
<tr>
<td>**</td>
<td>匹配任意长度字符，包含包名分隔符(.)</td>
</tr>
<tr>
<td>***</td>
<td>匹配任意参数类型</td>
</tr>
</tbody></table>
<ul>
<li>指定混淆时可使用字典<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">-applymapping filename 指定重用一个已经写好了的map文件作为新旧元素名的映射。</span><br><span class="line">-obfuscationdictionary filename 指定一个文本文件用来生成混淆后的名字。</span><br><span class="line">-classobfuscationdictionary filename 指定一个混淆类名的字典</span><br><span class="line">-packageobfuscationdictionary filename 指定一个混淆包名的字典</span><br><span class="line">-overloadaggressively 混淆的时候大量使用重载，多个方法名使用同一个混淆名（慎用）</span><br></pre></td></tr></table></figure></li>
</ul>
<h2 id="公共模板"><a href="#公共模板" class="headerlink" title="公共模板"></a>公共模板</h2><figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br><span class="line">125</span><br><span class="line">126</span><br><span class="line">127</span><br><span class="line">128</span><br><span class="line">129</span><br><span class="line">130</span><br><span class="line">131</span><br><span class="line">132</span><br><span class="line">133</span><br><span class="line">134</span><br><span class="line">135</span><br><span class="line">136</span><br><span class="line">137</span><br><span class="line">138</span><br><span class="line">139</span><br><span class="line">140</span><br><span class="line">141</span><br><span class="line">142</span><br><span class="line">143</span><br><span class="line">144</span><br></pre></td><td class="code"><pre><span class="line">#############################################</span><br><span class="line">#</span><br><span class="line"># 对于一些基本指令的添加</span><br><span class="line">#</span><br><span class="line">#############################################</span><br><span class="line"># 代码混淆压缩比，在 0~7 之间，默认为 5，一般不做修改</span><br><span class="line">-optimizationpasses 5</span><br><span class="line"></span><br><span class="line"># 混合时不使用大小写混合，混合后的类名为小写</span><br><span class="line">-dontusemixedcaseclassnames</span><br><span class="line"></span><br><span class="line"># 指定不去忽略非公共库的类</span><br><span class="line">-dontskipnonpubliclibraryclasses</span><br><span class="line"></span><br><span class="line"># 这句话能够使我们的项目混淆后产生映射文件</span><br><span class="line"># 包含有类名-&gt;混淆后类名的映射关系</span><br><span class="line">-verbose</span><br><span class="line"></span><br><span class="line"># 指定不去忽略非公共库的类成员</span><br><span class="line">-dontskipnonpubliclibraryclassmembers</span><br><span class="line"></span><br><span class="line"># 不做预校验，preverify 是 proguard 的四个步骤之一，Android 不需要 preverify，去掉这一步能够加快混淆速度。</span><br><span class="line">-dontpreverify</span><br><span class="line"></span><br><span class="line"># 保留 Annotation 不混淆</span><br><span class="line">-keepattributes *Annotation*,InnerClasses</span><br><span class="line"></span><br><span class="line"># 避免混淆泛型</span><br><span class="line">-keepattributes Signature</span><br><span class="line"></span><br><span class="line"># 抛出异常时保留代码行号</span><br><span class="line">-keepattributes SourceFile,LineNumberTable</span><br><span class="line"></span><br><span class="line"># 指定混淆是采用的算法，后面的参数是一个过滤器</span><br><span class="line"># 这个过滤器是谷歌推荐的算法，一般不做更改</span><br><span class="line">-optimizations !code/simplification/cast,!field/*,!class/merging/*</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">#############################################</span><br><span class="line">#</span><br><span class="line"># Android开发中一些需要保留的公共部分</span><br><span class="line">#</span><br><span class="line">#############################################</span><br><span class="line"></span><br><span class="line"># 保留我们使用的四大组件，自定义的 Application 等等这些类不被混淆</span><br><span class="line"># 因为这些子类都有可能被外部调用</span><br><span class="line">-keep public class * extends android.app.Activity</span><br><span class="line">-keep public class * extends android.app.Appliction</span><br><span class="line">-keep public class * extends android.app.Service</span><br><span class="line">-keep public class * extends android.content.BroadcastReceiver</span><br><span class="line">-keep public class * extends android.content.ContentProvider</span><br><span class="line">-keep public class * extends android.app.backup.BackupAgentHelper</span><br><span class="line">-keep public class * extends android.preference.Preference</span><br><span class="line">-keep public class * extends android.view.View</span><br><span class="line">-keep public class com.android.vending.licensing.ILicensingService</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"># 保留 support 下的所有类及其内部类</span><br><span class="line">-keep class android.support.** &#123; *; &#125;</span><br><span class="line"></span><br><span class="line"># 保留继承的</span><br><span class="line">-keep public class * extends android.support.v4.**</span><br><span class="line">-keep public class * extends android.support.v7.**</span><br><span class="line">-keep public class * extends android.support.annotation.**</span><br><span class="line"></span><br><span class="line"># 保留 R 下面的资源</span><br><span class="line">-keep class **.R$* &#123; *; &#125;</span><br><span class="line"></span><br><span class="line"># 保留本地 native 方法不被混淆</span><br><span class="line">-keepclasseswithmembernames class * &#123;</span><br><span class="line">    native &lt;methods&gt;;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"># 保留在 Activity 中的方法参数是view的方法，</span><br><span class="line"># 这样以来我们在 layout 中写的 onClick 就不会被影响</span><br><span class="line">-keepclassmembers class * extends android.app.Activity &#123;</span><br><span class="line">    public void *(android.view.View);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"># 保留枚举类不被混淆</span><br><span class="line">-keepclassmembers enum * &#123;</span><br><span class="line">    public static **[] values();</span><br><span class="line">    public static ** valueOf(java.lang.String);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"># 保留我们自定义控件（继承自 View）不被混淆</span><br><span class="line">-keep public class * extends android.view.View &#123;</span><br><span class="line">    *** get*();</span><br><span class="line">    void set*(***);</span><br><span class="line">    public &lt;init&gt;(android.content.Context);</span><br><span class="line">    public &lt;init&gt;(android.content.Context, android.util.AttributeSet);</span><br><span class="line">    public &lt;init&gt;(android.content.Context, android.util.AttributeSet, int);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"># 保留 Parcelable 序列化类不被混淆</span><br><span class="line">-keep class * implements android.os.Parcelable &#123;</span><br><span class="line">    public static final android.os.Parcelable$Creator *;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"># 保留 Serializable 序列化的类不被混淆</span><br><span class="line">-keepnames class * implements java.io.Serializable</span><br><span class="line">-keepclassmembers class * implements java.io.Serializable &#123;</span><br><span class="line">    static final long serialVersionUID;</span><br><span class="line">    private static final java.io.ObjectStreamField[] serialPersistentFields;</span><br><span class="line">    !static !transient &lt;fields&gt;;</span><br><span class="line">    !private &lt;fields&gt;;</span><br><span class="line">    !private &lt;methods&gt;;</span><br><span class="line">    private void writeObject(java.io.ObjectOutputStream);</span><br><span class="line">    private void readObject(java.io.ObjectInputStream);</span><br><span class="line">    java.lang.Object writeReplace();</span><br><span class="line">    java.lang.Object readResolve();</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"># 对于带有回调函数的 onXXEvent、**On*Listener 的，不能被混淆</span><br><span class="line">-keepclassmembers class * &#123;</span><br><span class="line">    void *(**On*Event);</span><br><span class="line">    void *(**On*Listener);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"># webView 处理，项目中没有使用到 webView 忽略即可</span><br><span class="line">-keepclassmembers class fqcn.of.javascript.interface.for.webview &#123;</span><br><span class="line">    public *;</span><br><span class="line">&#125;</span><br><span class="line">-keepclassmembers class * extends android.webkit.webViewClient &#123;</span><br><span class="line">    public void *(android.webkit.WebView, java.lang.String, android.graphics.Bitmap);</span><br><span class="line">    public boolean *(android.webkit.WebView, java.lang.String);</span><br><span class="line">&#125;</span><br><span class="line">-keepclassmembers class * extends android.webkit.webViewClient &#123;</span><br><span class="line">    public void *(android.webkit.webView, java.lang.String);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"># js</span><br><span class="line">-keepattributes JavascriptInterface</span><br><span class="line">-keep class android.webkit.JavascriptInterface &#123; *; &#125;</span><br><span class="line">-keepclassmembers class * &#123;</span><br><span class="line">    @android.webkit.JavascriptInterface &lt;methods&gt;;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"># @Keep</span><br><span class="line">-keep,allowobfuscation @interface android.support.annotation.Keep</span><br><span class="line">-keep @android.support.annotation.Keep class *</span><br><span class="line">-keepclassmembers class * &#123;</span><br><span class="line">    @android.support.annotation.Keep *;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="常用的自定义混淆规则"><a href="#常用的自定义混淆规则" class="headerlink" title="常用的自定义混淆规则"></a>常用的自定义混淆规则</h2><figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br></pre></td><td class="code"><pre><span class="line"># 通配符*，匹配任意长度字符，但不含包名分隔符(.)</span><br><span class="line"># 通配符**，匹配任意长度字符，并且包含包名分隔符(.)</span><br><span class="line"></span><br><span class="line"># 不混淆某个类</span><br><span class="line">-keep public class com.jasonwu.demo.Test &#123; *; &#125;</span><br><span class="line"></span><br><span class="line"># 不混淆某个包所有的类</span><br><span class="line">-keep class com.jasonwu.demo.test.** &#123; *; &#125;</span><br><span class="line"></span><br><span class="line"># 不混淆某个类的子类</span><br><span class="line">-keep public class * com.jasonwu.demo.Test &#123; *; &#125;</span><br><span class="line"></span><br><span class="line"># 不混淆所有类名中包含了 ``model`` 的类及其成员</span><br><span class="line">-keep public class **.*model*.** &#123;*;&#125;</span><br><span class="line"></span><br><span class="line"># 不混淆某个接口的实现</span><br><span class="line">-keep class * implements com.jasonwu.demo.TestInterface &#123; *; &#125;</span><br><span class="line"></span><br><span class="line"># 不混淆某个类的构造方法</span><br><span class="line">-keepclassmembers class com.jasonwu.demo.Test &#123; </span><br><span class="line">  public <span class="tag">&lt;<span class="name">init</span>&gt;</span>(); </span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"># 不混淆某个类的特定的方法</span><br><span class="line">-keepclassmembers class com.jasonwu.demo.Test &#123; </span><br><span class="line">  public void test(java.lang.String); </span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>


<h2 id="aar中增加独立的混淆配置"><a href="#aar中增加独立的混淆配置" class="headerlink" title="aar中增加独立的混淆配置"></a>aar中增加独立的混淆配置</h2><p><code>build.gralde</code></p>
<figure class="highlight gradle"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">android &#123;</span><br><span class="line">    ···</span><br><span class="line">    defaultConfig &#123;</span><br><span class="line">        ···</span><br><span class="line">        consumerProguardFile <span class="string">&#x27;proguard-rules.pro&#x27;</span></span><br><span class="line">    &#125;</span><br><span class="line">    ···</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="检查混淆和追踪异常"><a href="#检查混淆和追踪异常" class="headerlink" title="检查混淆和追踪异常"></a>检查混淆和追踪异常</h2><p>开启 Proguard 功能，则每次构建时 ProGuard 都会输出下列文件：</p>
<ul>
<li><p>dump.txt<br>说明 APK 中所有类文件的内部结构。</p>
</li>
<li><p>mapping.txt<br>提供原始与混淆过的类、方法和字段名称之间的转换。</p>
</li>
<li><p>seeds.txt<br>列出未进行混淆的类和成员。</p>
</li>
<li><p>usage.txt<br>列出从 APK 移除的代码。</p>
</li>
</ul>
<p>这些文件保存在 &#x2F;build&#x2F;outputs&#x2F;mapping&#x2F;release&#x2F; 中。我们可以查看 seeds.txt 里面是否是我们需要保留的，以及 usage.txt 里查看是否有误删除的代码。 mapping.txt 文件很重要，由于我们的部分代码是经过重命名的，如果该部分出现 bug，对应的异常堆栈信息里的类或成员也是经过重命名的，难以定位问题。我们可以用 retrace 脚本（在 Windows 上为 retrace.bat；在 Mac&#x2F;Linux 上为 retrace.sh）。它位于 &#x2F;tools&#x2F;proguard&#x2F; 目录中。该脚本利用 mapping.txt 文件和你的异常堆栈文件生成没有经过混淆的异常堆栈文件,这样就可以看清是哪里出问题了。使用 retrace 工具的语法如下：</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">retrace.bat|retrace.sh [-verbose] mapping.txt [&lt;stacktrace_file&gt;]</span><br></pre></td></tr></table></figure>

<h1 id="架构"><a href="#架构" class="headerlink" title="架构"></a>架构</h1><h2 id="MVC"><a href="#MVC" class="headerlink" title="MVC"></a>MVC</h2><p><img src="https://mmbiz.qpic.cn/mmbiz_png/zKFJDM5V3Wy5xbLTp6JMMdouZiavFxyYCwLhGyLdicyLzgUDKFTZVt1OgU6iaSx2IUwnygzmQzW7Renaa8hmQ62cQ/640?wx_fmt=png&tp=webp&wxfrom=5&wx_lazy=1&wx_co=1"></p>
<p>在 Android 中，三者的关系如下：</p>
<p><img src="https://mmbiz.qpic.cn/mmbiz_png/zKFJDM5V3Wy5xbLTp6JMMdouZiavFxyYCicNvEVMO9vDgukUR29Z1DCacZJwmmH1EEb7gUOZmDxolWexP01O8jfg/640?wx_fmt=png&tp=webp&wxfrom=5&wx_lazy=1&wx_co=1"></p>
<p>由于在 Android 中 xml 布局的功能性太弱，所以 Activity 承担了绝大部分的工作，所以在 Android 中 mvc 更像：</p>
<p><img src="https://mmbiz.qpic.cn/mmbiz_png/zKFJDM5V3Wy5xbLTp6JMMdouZiavFxyYCOq89MLQX4UM3dgBTQfU72desHb1XbOWRQZINnXOCCdZCuicUiaTHhtEg/640?wx_fmt=png&tp=webp&wxfrom=5&wx_lazy=1&wx_co=1"></p>
<p>总结：</p>
<ul>
<li>具有一定的分层，model 解耦，controller 和 view 并没有解耦</li>
<li>controller 和 view 在 Android 中无法做到彻底分离，Controller 变得臃肿不堪</li>
<li>易于理解、开发速度快、可维护性高</li>
</ul>
<h2 id="MVP"><a href="#MVP" class="headerlink" title="MVP"></a>MVP</h2><p><img src="https://mmbiz.qpic.cn/mmbiz_png/zKFJDM5V3Wy5xbLTp6JMMdouZiavFxyYCLVgibsuVQFguBI8FBdZibLNfpvbpd6njkdGWdyR2UL6TzMOhKHFqLC0Q/640?wx_fmt=png&tp=webp&wxfrom=5&wx_lazy=1&wx_co=1"></p>
<p>通过引入接口 BaseView，让相应的视图组件如 Activity，Fragment去实现 BaseView，把业务逻辑放在 presenter 层中，弱化 Model 只有跟 view 相关的操作都由 View 层去完成。</p>
<p>总结：</p>
<ul>
<li>彻底解决了 MVC 中 View 和 Controller 傻傻分不清楚的问题</li>
<li>但是随着业务逻辑的增加，一个页面可能会非常复杂，UI 的改变是非常多，会有非常多的 case，这样就会造成 View 的接口会很庞大</li>
<li>更容易单元测试</li>
</ul>
<h2 id="MVVM"><a href="#MVVM" class="headerlink" title="MVVM"></a>MVVM</h2><p><img src="https://mmbiz.qpic.cn/mmbiz_png/zKFJDM5V3Wy5xbLTp6JMMdouZiavFxyYCMygIDD6xo5djkq6Y3jZo53sT2A4kKNaz8JEVRwmUnTmcAwJm0pZVWg/640?wx_fmt=png&tp=webp&wxfrom=5&wx_lazy=1&wx_co=1"></p>
<p>在 MVP 中 View 和 Presenter 要相互持有，方便调用对方，而在 MVP 中 View 和 ViewModel 通过 Binding 进行关联，他们之前的关联处理通过  DataBinding 完成。</p>
<p>总结：</p>
<ul>
<li>很好的解决了 MVC 和 MVP 的问题</li>
<li>视图状态较多，ViewModel 的构建和维护的成本都会比较高</li>
<li>但是由于数据和视图的双向绑定，导致出现问题时不太好定位来源</li>
</ul>
<h1 id="Jetpack"><a href="#Jetpack" class="headerlink" title="Jetpack"></a>Jetpack</h1><h2 id="架构-1"><a href="#架构-1" class="headerlink" title="架构"></a>架构</h2><p><img src="https://developer.android.google.cn/topic/libraries/architecture/images/final-architecture.png"></p>
<h2 id="使用示例-1"><a href="#使用示例-1" class="headerlink" title="使用示例"></a>使用示例</h2><p><code>build.gradle</code></p>
<figure class="highlight groovy"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line">android &#123;</span><br><span class="line">    ···</span><br><span class="line">    dataBinding &#123;</span><br><span class="line">        enabled = <span class="literal">true</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line">dependencies &#123;</span><br><span class="line">    ···</span><br><span class="line">    implementation <span class="string">&quot;androidx.fragment:fragment-ktx:$rootProject.fragmentVersion&quot;</span></span><br><span class="line">    implementation <span class="string">&quot;androidx.lifecycle:lifecycle-extensions:$rootProject.lifecycleVersion&quot;</span></span><br><span class="line">    implementation <span class="string">&quot;androidx.lifecycle:lifecycle-livedata-ktx:$rootProject.lifecycleVersion&quot;</span></span><br><span class="line">    implementation <span class="string">&quot;androidx.lifecycle:lifecycle-viewmodel-ktx:$rootProject.lifecycleVersion&quot;</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><code>fragment_plant_detail.xml</code></p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">layout</span> <span class="attr">xmlns:android</span>=<span class="string">&quot;http://schemas.android.com/apk/res/android&quot;</span></span></span><br><span class="line"><span class="tag">    <span class="attr">xmlns:app</span>=<span class="string">&quot;http://schemas.android.com/apk/res-auto&quot;</span></span></span><br><span class="line"><span class="tag">    <span class="attr">xmlns:tools</span>=<span class="string">&quot;http://schemas.android.com/tools&quot;</span>&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="tag">&lt;<span class="name">data</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">variable</span></span></span><br><span class="line"><span class="tag">            <span class="attr">name</span>=<span class="string">&quot;viewModel&quot;</span></span></span><br><span class="line"><span class="tag">            <span class="attr">type</span>=<span class="string">&quot;com.google.samples.apps.sunflower.viewmodels.PlantDetailViewModel&quot;</span> /&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">data</span>&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="tag">&lt;<span class="name">androidx.constraintlayout.widget.ConstraintLayout</span></span></span><br><span class="line"><span class="tag">        <span class="attr">android:layout_width</span>=<span class="string">&quot;match_parent&quot;</span></span></span><br><span class="line"><span class="tag">        <span class="attr">android:layout_height</span>=<span class="string">&quot;match_parent&quot;</span>&gt;</span></span><br><span class="line"></span><br><span class="line">        <span class="tag">&lt;<span class="name">TextView</span></span></span><br><span class="line"><span class="tag">            ···</span></span><br><span class="line"><span class="tag">            <span class="attr">android:text</span>=<span class="string">&quot;@&#123;viewModel.plant.name&#125;&quot;</span>/&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="tag">&lt;/<span class="name">androidx.constraintlayout.widget.ConstraintLayout</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">layout</span>&gt;</span></span><br></pre></td></tr></table></figure>


<p><code>PlantDetailFragment.kt</code></p>
<figure class="highlight kotlin"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">PlantDetailFragment</span> : <span class="type">Fragment</span>() &#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">val</span> args: PlantDetailFragmentArgs <span class="keyword">by</span> navArgs()</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">lateinit</span> <span class="keyword">var</span> shareText: String</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">val</span> plantDetailViewModel: PlantDetailViewModel <span class="keyword">by</span> viewModels &#123;</span><br><span class="line">        InjectorUtils.providePlantDetailViewModelFactory(requireActivity(), args.plantId)</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">override</span> <span class="function"><span class="keyword">fun</span> <span class="title">onCreateView</span><span class="params">(</span></span></span><br><span class="line"><span class="params"><span class="function">        inflater: <span class="type">LayoutInflater</span>,</span></span></span><br><span class="line"><span class="params"><span class="function">        container: <span class="type">ViewGroup</span>?,</span></span></span><br><span class="line"><span class="params"><span class="function">        savedInstanceState: <span class="type">Bundle</span>?</span></span></span><br><span class="line"><span class="params"><span class="function">    )</span></span>: View? &#123;</span><br><span class="line">        <span class="keyword">val</span> binding = DataBindingUtil.inflate&lt;FragmentPlantDetailBinding&gt;(</span><br><span class="line">                inflater, R.layout.fragment_plant_detail, container, <span class="literal">false</span>).apply &#123;</span><br><span class="line">            viewModel = plantDetailViewModel</span><br><span class="line">            lifecycleOwner = <span class="keyword">this</span><span class="symbol">@PlantDetailFragment</span></span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        plantDetailViewModel.plant.observe(<span class="keyword">this</span>) &#123; plant -&gt;</span><br><span class="line">            <span class="comment">// 更新相关 UI</span></span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">return</span> binding.root</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><code>Plant.kt</code></p>
<figure class="highlight kotlin"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">data</span> <span class="keyword">class</span> <span class="title class_">Plant</span> (</span><br><span class="line">    <span class="keyword">val</span> name: String</span><br><span class="line">)</span><br></pre></td></tr></table></figure>

<p><code>PlantDetailViewModel.kt</code></p>
<figure class="highlight kotlin"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">PlantDetailViewModel</span>(</span><br><span class="line">    plantRepository: PlantRepository,</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">val</span> plantId: String</span><br><span class="line">) : ViewModel() &#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">val</span> plant: LiveData&lt;Plant&gt;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">override</span> <span class="function"><span class="keyword">fun</span> <span class="title">onCleared</span><span class="params">()</span></span> &#123;</span><br><span class="line">        <span class="keyword">super</span>.onCleared()</span><br><span class="line">        viewModelScope.cancel()</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">init</span> &#123;</span><br><span class="line">        plant = plantRepository.getPlant(plantId)</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><code>PlantDetailViewModelFactory.kt</code></p>
<figure class="highlight kotlin"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">PlantDetailViewModelFactory</span>(</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">val</span> plantRepository: PlantRepository,</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">val</span> plantId: String</span><br><span class="line">) : ViewModelProvider.NewInstanceFactory() &#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Suppress(<span class="string">&quot;UNCHECKED_CAST&quot;</span>)</span></span><br><span class="line">    <span class="keyword">override</span> <span class="function"><span class="keyword">fun</span> <span class="type">&lt;T : ViewModel&gt;</span> <span class="title">create</span><span class="params">(modelClass: <span class="type">Class</span>&lt;<span class="type">T</span>&gt;)</span></span>: T &#123;</span><br><span class="line">        <span class="keyword">return</span> PlantDetailViewModel(plantRepository, plantId) <span class="keyword">as</span> T</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><code>InjectorUtils.kt</code></p>
<figure class="highlight kotlin"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">object</span> InjectorUtils &#123;</span><br><span class="line">    <span class="keyword">private</span> <span class="function"><span class="keyword">fun</span> <span class="title">getPlantRepository</span><span class="params">(context: <span class="type">Context</span>)</span></span>: PlantRepository &#123;</span><br><span class="line">        ···</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">fun</span> <span class="title">providePlantDetailViewModelFactory</span><span class="params">(</span></span></span><br><span class="line"><span class="params"><span class="function">        context: <span class="type">Context</span>,</span></span></span><br><span class="line"><span class="params"><span class="function">        plantId: <span class="type">String</span></span></span></span><br><span class="line"><span class="params"><span class="function">    )</span></span>: PlantDetailViewModelFactory &#123;</span><br><span class="line">        <span class="keyword">return</span> PlantDetailViewModelFactory(getPlantRepository(context), plantId)</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h1 id="NDK-开发"><a href="#NDK-开发" class="headerlink" title="NDK 开发"></a>NDK 开发</h1><blockquote>
<p>NDK 全称是 Native Development Kit，是一组可以让你在 Android 应用中编写实现 C&#x2F;C++ 的工具，可以在项目用自己写源代码构建，也可以利用现有的预构建库。</p>
</blockquote>
<p>使用 NDK 的使用目的有：</p>
<ul>
<li>从设备获取更好的性能以用于计算密集型应用，例如游戏或物理模拟  </li>
<li>重复使用自己或其他开发者的 C&#x2F;C++ 库，便利于跨平台。  </li>
<li>NDK 集成了譬如 OpenSL、Vulkan 等 API 规范的特定实现，以实现在 java 层无法做到的功能如提升音频性能等  </li>
<li>增加反编译难度</li>
</ul>
<h2 id="JNI-基础"><a href="#JNI-基础" class="headerlink" title="JNI 基础"></a>JNI 基础</h2><h3 id="数据类型"><a href="#数据类型" class="headerlink" title="数据类型"></a>数据类型</h3><ul>
<li>基本数据类型</li>
</ul>
<table>
<thead>
<tr>
<th>Java 类型</th>
<th>Native 类型</th>
<th>符号属性</th>
<th>字长</th>
</tr>
</thead>
<tbody><tr>
<td>boolean</td>
<td>jboolean</td>
<td>无符号</td>
<td>8位</td>
</tr>
<tr>
<td>byte</td>
<td>jbyte</td>
<td>无符号</td>
<td>8位</td>
</tr>
<tr>
<td>char</td>
<td>jchar</td>
<td>无符号</td>
<td>16位</td>
</tr>
<tr>
<td>short</td>
<td>jshort</td>
<td>有符号</td>
<td>16位</td>
</tr>
<tr>
<td>int</td>
<td>jnit</td>
<td>有符号</td>
<td>32位</td>
</tr>
<tr>
<td>long</td>
<td>jlong</td>
<td>有符号</td>
<td>64位</td>
</tr>
<tr>
<td>float</td>
<td>jfloat</td>
<td>有符号</td>
<td>32位</td>
</tr>
<tr>
<td>double</td>
<td>jdouble</td>
<td>有符号</td>
<td>64位</td>
</tr>
</tbody></table>
<ul>
<li>引用数据类型</li>
</ul>
<table>
<thead>
<tr>
<th>Java 引用类型</th>
<th>Native 类型</th>
<th>Java 引用类型</th>
<th>Native 类型</th>
</tr>
</thead>
<tbody><tr>
<td>All objects</td>
<td>jobject</td>
<td>char[]</td>
<td>jcharArray</td>
</tr>
<tr>
<td>java.lang.Class</td>
<td>jclass</td>
<td>short[]</td>
<td>jshortArray</td>
</tr>
<tr>
<td>java.lang.String</td>
<td>jstring</td>
<td>int[]</td>
<td>jintArray</td>
</tr>
<tr>
<td>Object[]</td>
<td>jobjectArray</td>
<td>long[]</td>
<td>jlongArray</td>
</tr>
<tr>
<td>boolean[]</td>
<td>jbooleanArray</td>
<td>float[]</td>
<td>jfloatArray</td>
</tr>
<tr>
<td>byte[]</td>
<td>jbyteArray</td>
<td>double[]</td>
<td>jdoubleArray</td>
</tr>
<tr>
<td>java.lang.Throwable</td>
<td>jthrowable</td>
<td></td>
<td></td>
</tr>
</tbody></table>
<h3 id="String-字符串函数操作"><a href="#String-字符串函数操作" class="headerlink" title="String 字符串函数操作"></a>String 字符串函数操作</h3><table>
<thead>
<tr>
<th>JNI 函数</th>
<th>描述</th>
</tr>
</thead>
<tbody><tr>
<td>GetStringChars &#x2F; ReleaseStringChars</td>
<td>获得或释放一个指向 Unicode 编码的字符串的指针（指 C&#x2F;C++ 字符串）</td>
</tr>
<tr>
<td>GetStringUTFChars &#x2F; ReleaseStringUTFChars</td>
<td>获得或释放一个指向 UTF-8 编码的字符串的指针（指 C&#x2F;C++ 字符串）</td>
</tr>
<tr>
<td>GetStringLength</td>
<td>返回 Unicode 编码的字符串的长度</td>
</tr>
<tr>
<td>getStringUTFLength</td>
<td>返回 UTF-8 编码的字符串的长度</td>
</tr>
<tr>
<td>NewString</td>
<td>将 Unicode 编码的 C&#x2F;C++ 字符串转换为 Java 字符串</td>
</tr>
<tr>
<td>NewStringUTF</td>
<td>将 UTF-8 编码的 C&#x2F;C++ 字符串转换为 Java 字符串</td>
</tr>
<tr>
<td>GetStringCritical &#x2F; ReleaseStringCritical</td>
<td>获得或释放一个指向字符串内容的指针(指 Java 字符串)</td>
</tr>
<tr>
<td>GetStringRegion</td>
<td>获取或者设置 Unicode 编码的字符串的指定范围的内容</td>
</tr>
<tr>
<td>GetStringUTFRegion</td>
<td>获取或者设置 UTF-8 编码的字符串的指定范围的内容</td>
</tr>
</tbody></table>
<h3 id="常用-JNI-访问-Java-对象方法"><a href="#常用-JNI-访问-Java-对象方法" class="headerlink" title="常用 JNI 访问 Java 对象方法"></a>常用 JNI 访问 Java 对象方法</h3><p><code>MyJob.java</code></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> com.example.myjniproject;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">MyJob</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="type">String</span> <span class="variable">JOB_STRING</span> <span class="operator">=</span> <span class="string">&quot;my_job&quot;</span>;</span><br><span class="line">    <span class="keyword">private</span> <span class="type">int</span> jobId;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="title function_">MyJob</span><span class="params">(<span class="type">int</span> jobId)</span> &#123;</span><br><span class="line">        <span class="built_in">this</span>.jobId = jobId;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="type">int</span> <span class="title function_">getJobId</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> jobId;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p><code>native-lib.cpp</code></p>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;jni.h&gt;</span></span></span><br><span class="line"></span><br><span class="line"><span class="keyword">extern</span> <span class="string">&quot;C&quot;</span></span><br><span class="line"><span class="function">JNIEXPORT jint JNICALL</span></span><br><span class="line"><span class="function"><span class="title">Java_com_example_myjniproject_MainActivity_getJobId</span><span class="params">(JNIEnv *env, jobject thiz, jobject job)</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 根据实力获取 class 对象</span></span><br><span class="line">    jclass jobClz = env-&gt;<span class="built_in">GetObjectClass</span>(job);</span><br><span class="line">    <span class="comment">// 根据类名获取 class 对象</span></span><br><span class="line">    jclass jobClz = env-&gt;<span class="built_in">FindClass</span>(<span class="string">&quot;com/example/myjniproject/MyJob&quot;</span>);</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 获取属性 id</span></span><br><span class="line">    jfieldID fieldId = env-&gt;<span class="built_in">GetFieldID</span>(jobClz, <span class="string">&quot;jobId&quot;</span>, <span class="string">&quot;I&quot;</span>);</span><br><span class="line">    <span class="comment">// 获取静态属性 id</span></span><br><span class="line">    jfieldID sFieldId = env-&gt;<span class="built_in">GetStaticFieldID</span>(jobClz, <span class="string">&quot;JOB_STRING&quot;</span>, <span class="string">&quot;Ljava/lang/String;&quot;</span>);</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 获取方法 id</span></span><br><span class="line">    jmethodID methodId = env-&gt;<span class="built_in">GetMethodID</span>(jobClz, <span class="string">&quot;getJobId&quot;</span>, <span class="string">&quot;()I&quot;</span>);</span><br><span class="line">    <span class="comment">// 获取构造方法 id</span></span><br><span class="line">    jmethodID  initMethodId = env-&gt;<span class="built_in">GetMethodID</span>(jobClz, <span class="string">&quot;&lt;init&gt;&quot;</span>, <span class="string">&quot;(I)V&quot;</span>);</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 根据对象属性 id 获取该属性值</span></span><br><span class="line">    jint id = env-&gt;<span class="built_in">GetIntField</span>(job, fieldId);</span><br><span class="line">    <span class="comment">// 根据对象方法 id 调用该方法</span></span><br><span class="line">    jint id = env-&gt;<span class="built_in">CallIntMethod</span>(job, methodId);</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 创建新的对象</span></span><br><span class="line">    jobject newJob = env-&gt;<span class="built_in">NewObject</span>(jobClz, initMethodId, <span class="number">10</span>);</span><br><span class="line"></span><br><span class="line">    <span class="keyword">return</span> id;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="NDK-开发-1"><a href="#NDK-开发-1" class="headerlink" title="NDK 开发"></a>NDK 开发</h2><h3 id="基础开发流程"><a href="#基础开发流程" class="headerlink" title="基础开发流程"></a>基础开发流程</h3><ul>
<li><p>在 java 中声明 native 方法</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">MainActivity</span> <span class="keyword">extends</span> <span class="title class_">AppCompatActivity</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// Used to load the &#x27;native-lib&#x27; library on application startup.</span></span><br><span class="line">    <span class="keyword">static</span> &#123;</span><br><span class="line">        System.loadLibrary(<span class="string">&quot;native-lib&quot;</span>);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">protected</span> <span class="keyword">void</span> <span class="title function_">onCreate</span><span class="params">(Bundle savedInstanceState)</span> &#123;</span><br><span class="line">        <span class="built_in">super</span>.onCreate(savedInstanceState);</span><br><span class="line">        setContentView(R.layout.activity_main);</span><br><span class="line"></span><br><span class="line">        Log.d(<span class="string">&quot;MainActivity&quot;</span>, stringFromJNI());</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">native</span> String <span class="title function_">stringFromJNI</span><span class="params">()</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
</li>
<li><p>在 <code>app/src/main</code> 目录下新建 cpp 目录，新建相关 cpp 文件，实现相关方法（AS 可用快捷键快速生成）</p>
</li>
</ul>
<p><code>native-lib.cpp</code></p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">#include &lt;jni.h&gt;</span><br><span class="line"></span><br><span class="line">extern &quot;C&quot; JNIEXPORT jstring JNICALL</span><br><span class="line">Java_com_example_myjniproject_MainActivity_stringFromJNI(</span><br><span class="line">        JNIEnv *env,</span><br><span class="line">        jobject /* this */) &#123;</span><br><span class="line">    std::string hello = &quot;Hello from C++&quot;;</span><br><span class="line">    return env-&gt;NewStringUTF(hello.c_str());</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<blockquote>
<ul>
<li>函数名的格式遵循遵循如下规则：Java_包名_类名_方法名。</li>
<li>extern “C” 指定采用 C 语言的命名风格来编译，否则由于 C 与 C++ 风格不同，导致链接时无法找到具体的函数</li>
<li>JNIEnv*：表示一个指向 JNI 环境的指针，可以通过他来访问 JNI 提供的接口方法</li>
<li>jobject：表示 java 对象中的 this</li>
<li>JNIEXPORT 和 JNICALL：JNI 所定义的宏，可以在 jni.h 头文件中查找到</li>
</ul>
</blockquote>
<ul>
<li>通过 CMake 或者 ndk-build 构建动态库</li>
</ul>
<h3 id="System-loadLibrary"><a href="#System-loadLibrary" class="headerlink" title="System.loadLibrary()"></a>System.loadLibrary()</h3><p><code>java/lang/System.java</code>:</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@CallerSensitive</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">load</span><span class="params">(String filename)</span> &#123;</span><br><span class="line">    Runtime.getRuntime().load0(Reflection.getCallerClass(), filename);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<ul>
<li>调用 <code>Runtime</code> 相关 native 方法</li>
</ul>
<p><code>java/lang/Runtime.java</code>:</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">native</span> String <span class="title function_">nativeLoad</span><span class="params">(String filename, ClassLoader loader, Class&lt;?&gt; caller)</span>;</span><br></pre></td></tr></table></figure>

<ul>
<li>native 方法的实现如下：</li>
</ul>
<p><code>dalvik/vm/native/java_lang_Runtime.cpp</code>:</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="type">static</span> <span class="type">void</span> <span class="title">Dalvik_java_lang_Runtime_nativeLoad</span><span class="params">(<span class="type">const</span> u4* args,</span></span></span><br><span class="line"><span class="params"><span class="function">    JValue* pResult)</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    ···</span><br><span class="line">    <span class="type">bool</span> success;</span><br><span class="line"></span><br><span class="line">    <span class="built_in">assert</span>(fileNameObj != <span class="literal">NULL</span>);</span><br><span class="line">    <span class="comment">// 将 Java 的 library path String 转换到 native 的 String</span></span><br><span class="line">    fileName = <span class="built_in">dvmCreateCstrFromString</span>(fileNameObj);</span><br><span class="line"></span><br><span class="line">    success = <span class="built_in">dvmLoadNativeCode</span>(fileName, classLoader, &amp;reason);</span><br><span class="line">    <span class="keyword">if</span> (!success) &#123;</span><br><span class="line">        <span class="type">const</span> <span class="type">char</span>* msg = (reason != <span class="literal">NULL</span>) ? reason : <span class="string">&quot;unknown failure&quot;</span>;</span><br><span class="line">        result = <span class="built_in">dvmCreateStringFromCstr</span>(msg);</span><br><span class="line">        <span class="built_in">dvmReleaseTrackedAlloc</span>((Object*) result, <span class="literal">NULL</span>);</span><br><span class="line">    &#125;</span><br><span class="line">    ···</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<ul>
<li><code>dvmLoadNativeCode</code> 函数实现如下：</li>
</ul>
<p><code>dalvik/vm/Native.cpp</code></p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="type">bool</span> <span class="title">dvmLoadNativeCode</span><span class="params">(<span class="type">const</span> <span class="type">char</span>* pathName, Object* classLoader,</span></span></span><br><span class="line"><span class="params"><span class="function">        <span class="type">char</span>** detail)</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    SharedLib* pEntry;</span><br><span class="line">    <span class="type">void</span>* handle;</span><br><span class="line">    ···</span><br><span class="line">    *detail = <span class="literal">NULL</span>;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 如果已经加载过了，则直接返回 true</span></span><br><span class="line">    pEntry = <span class="built_in">findSharedLibEntry</span>(pathName);</span><br><span class="line">    <span class="keyword">if</span> (pEntry != <span class="literal">NULL</span>) &#123;</span><br><span class="line">        <span class="keyword">if</span> (pEntry-&gt;classLoader != classLoader) &#123;</span><br><span class="line">            ···</span><br><span class="line">            <span class="keyword">return</span> <span class="literal">false</span>;</span><br><span class="line">        &#125;</span><br><span class="line">        ···</span><br><span class="line">        <span class="keyword">if</span> (!<span class="built_in">checkOnLoadResult</span>(pEntry))</span><br><span class="line">            <span class="keyword">return</span> <span class="literal">false</span>;</span><br><span class="line">        <span class="keyword">return</span> <span class="literal">true</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    Thread* self = <span class="built_in">dvmThreadSelf</span>();</span><br><span class="line">    ThreadStatus oldStatus = <span class="built_in">dvmChangeStatus</span>(self, THREAD_VMWAIT);</span><br><span class="line">    <span class="comment">// 把.so mmap 到进程空间，并把 func 等相关信息填充到 soinfo 中</span></span><br><span class="line">    handle = <span class="built_in">dlopen</span>(pathName, RTLD_LAZY);</span><br><span class="line">    <span class="built_in">dvmChangeStatus</span>(self, oldStatus);</span><br><span class="line">    ···</span><br><span class="line">    <span class="comment">// 创建一个新的 entry</span></span><br><span class="line">    SharedLib* pNewEntry;</span><br><span class="line">    pNewEntry = (SharedLib*) <span class="built_in">calloc</span>(<span class="number">1</span>, <span class="built_in">sizeof</span>(SharedLib));</span><br><span class="line">    pNewEntry-&gt;pathName = <span class="built_in">strdup</span>(pathName);</span><br><span class="line">    pNewEntry-&gt;handle = handle;</span><br><span class="line">    pNewEntry-&gt;classLoader = classLoader;</span><br><span class="line">    <span class="built_in">dvmInitMutex</span>(&amp;pNewEntry-&gt;onLoadLock);</span><br><span class="line">    <span class="built_in">pthread_cond_init</span>(&amp;pNewEntry-&gt;onLoadCond, <span class="literal">NULL</span>);</span><br><span class="line">    pNewEntry-&gt;onLoadThreadId = self-&gt;threadId;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 尝试添加到列表中</span></span><br><span class="line">    SharedLib* pActualEntry = <span class="built_in">addSharedLibEntry</span>(pNewEntry);</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> (pNewEntry != pActualEntry) &#123;</span><br><span class="line">        ···</span><br><span class="line">        <span class="built_in">freeSharedLibEntry</span>(pNewEntry);</span><br><span class="line">        <span class="keyword">return</span> <span class="built_in">checkOnLoadResult</span>(pActualEntry);</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">        ···</span><br><span class="line">        <span class="type">bool</span> result = <span class="literal">true</span>;</span><br><span class="line">        <span class="type">void</span>* vonLoad;</span><br><span class="line">        <span class="type">int</span> version;</span><br><span class="line">        <span class="comment">// 调用该 so 库的 JNI_OnLoad 方法</span></span><br><span class="line">        vonLoad = <span class="built_in">dlsym</span>(handle, <span class="string">&quot;JNI_OnLoad&quot;</span>);</span><br><span class="line">        <span class="keyword">if</span> (vonLoad == <span class="literal">NULL</span>) &#123;</span><br><span class="line">            ···</span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">            <span class="comment">// 调用 JNI_Onload 方法，重写类加载器。</span></span><br><span class="line">            OnLoadFunc func = (OnLoadFunc)vonLoad;</span><br><span class="line">            Object* prevOverride = self-&gt;classLoaderOverride;</span><br><span class="line"></span><br><span class="line">            self-&gt;classLoaderOverride = classLoader;</span><br><span class="line">            oldStatus = <span class="built_in">dvmChangeStatus</span>(self, THREAD_NATIVE);</span><br><span class="line">            ···</span><br><span class="line">            version = (*func)(gDvmJni.jniVm, <span class="literal">NULL</span>);</span><br><span class="line">            <span class="built_in">dvmChangeStatus</span>(self, oldStatus);</span><br><span class="line">            self-&gt;classLoaderOverride = prevOverride;</span><br><span class="line"></span><br><span class="line">            <span class="keyword">if</span> (version != JNI_VERSION_1_2 &amp;&amp; version != JNI_VERSION_1_4 &amp;&amp;</span><br><span class="line">                version != JNI_VERSION_1_6)</span><br><span class="line">            &#123;</span><br><span class="line">                ···</span><br><span class="line">                result = <span class="literal">false</span>;</span><br><span class="line">            &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">                ···</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">if</span> (result)</span><br><span class="line">            pNewEntry-&gt;onLoadResult = kOnLoadOkay;</span><br><span class="line">        <span class="keyword">else</span></span><br><span class="line">            pNewEntry-&gt;onLoadResult = kOnLoadFailed;</span><br><span class="line"></span><br><span class="line">        pNewEntry-&gt;onLoadThreadId = <span class="number">0</span>;</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 释放锁资源 </span></span><br><span class="line">        <span class="built_in">dvmLockMutex</span>(&amp;pNewEntry-&gt;onLoadLock);</span><br><span class="line">        <span class="built_in">pthread_cond_broadcast</span>(&amp;pNewEntry-&gt;onLoadCond);</span><br><span class="line">        <span class="built_in">dvmUnlockMutex</span>(&amp;pNewEntry-&gt;onLoadLock);</span><br><span class="line">        <span class="keyword">return</span> result;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<!-- ### native 方法调用原理
- 虚拟机调用一个方法时，发现如果这是一个 native 方法，则使用 Method 对象中的nativeFunc 函数指针对象调用。

``dalvik2/vm/interp/Stack.cpp``:
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br></pre></td><td class="code"><pre><span class="line"><span class="function">Object* <span class="title">dvmInvokeMethod</span><span class="params">(Object* obj, <span class="type">const</span> Method* method,</span></span></span><br><span class="line"><span class="params"><span class="function">    ArrayObject* argList, ArrayObject* params, ClassObject* returnType,</span></span></span><br><span class="line"><span class="params"><span class="function">    <span class="type">bool</span> noAccessCheck)</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    ···</span><br><span class="line">    <span class="keyword">if</span> (<span class="built_in">dvmIsNativeMethod</span>(method)) &#123;</span><br><span class="line">        <span class="built_in">TRACE_METHOD_ENTER</span>(self, method);</span><br><span class="line">        (*method-&gt;nativeFunc)((u4*)self-&gt;interpSave.curFrame, &amp;retval, method, self);</span><br><span class="line">        <span class="built_in">TRACE_METHOD_EXIT</span>(self, method);</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">        <span class="built_in">dvmInterpret</span>(self, method, &amp;retval);</span><br><span class="line">    &#125;</span><br><span class="line">    ···</span><br><span class="line">&#125;</span><br><span class="line">``` --&gt;</span><br><span class="line"></span><br><span class="line">## CMake 构建 NDK 项目</span><br><span class="line">&gt; CMake 是一个开源的跨平台工具系列，旨在构建，测试和打包软件，从 Android Studio <span class="number">2.2</span> 开始，Android Sudio 默认地使用 CMake 与 Gradle 搭配使用来构建原生库。</span><br><span class="line"></span><br><span class="line">启动方式只需要在 ``app/build.gradle`` 中添加相关：</span><br><span class="line">```groovy</span><br><span class="line">android &#123;</span><br><span class="line">    ···</span><br><span class="line">    defaultConfig &#123;</span><br><span class="line">        ···</span><br><span class="line">        externalNativeBuild &#123;</span><br><span class="line">            cmake &#123;</span><br><span class="line">                cppFlags <span class="string">&quot;&quot;</span></span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        ndk &#123;</span><br><span class="line">            abiFilters <span class="string">&#x27;arm64-v8a&#x27;</span>, <span class="string">&#x27;armeabi-v7a&#x27;</span></span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    ···</span><br><span class="line">    externalNativeBuild &#123;</span><br><span class="line">        cmake &#123;</span><br><span class="line">            path <span class="string">&quot;CMakeLists.txt&quot;</span></span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>然后在对应目录新建一个 <code>CMakeLists.txt</code> 文件：</p>
<figure class="highlight txt"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br></pre></td><td class="code"><pre><span class="line"># 定义了所需 CMake 的最低版本</span><br><span class="line">cmake_minimum_required(VERSION 3.4.1)</span><br><span class="line"></span><br><span class="line"># add_library() 命令用来添加库</span><br><span class="line"># native-lib 对应着生成的库的名字</span><br><span class="line"># SHARED 代表为分享库</span><br><span class="line"># src/main/cpp/native-lib.cpp 则是指明了源文件的路径。</span><br><span class="line">add_library( # Sets the name of the library.</span><br><span class="line">        native-lib</span><br><span class="line"></span><br><span class="line">        # Sets the library as a shared library.</span><br><span class="line">        SHARED</span><br><span class="line"></span><br><span class="line">        # Provides a relative path to your source file(s).</span><br><span class="line">        src/main/cpp/native-lib.cpp)</span><br><span class="line"></span><br><span class="line"># find_library 命令添加到 CMake 构建脚本中以定位 NDK 库，并将其路径存储为一个变量。</span><br><span class="line"># 可以使用此变量在构建脚本的其他部分引用 NDK 库</span><br><span class="line">find_library( # Sets the name of the path variable.</span><br><span class="line">        log-lib</span><br><span class="line"></span><br><span class="line">        # Specifies the name of the NDK library that</span><br><span class="line">        # you want CMake to locate.</span><br><span class="line">        log)</span><br><span class="line"></span><br><span class="line"># 预构建的 NDK 库已经存在于 Android 平台上，因此，无需再构建或将其打包到 APK 中。</span><br><span class="line"># 由于 NDK 库已经是 CMake 搜索路径的一部分，只需要向 CMake 提供希望使用的库的名称，并将其关联到自己的原生库中</span><br><span class="line"></span><br><span class="line"># 要将预构建库关联到自己的原生库</span><br><span class="line">target_link_libraries( # Specifies the target library.</span><br><span class="line">        native-lib</span><br><span class="line"></span><br><span class="line">        # Links the target library to the log library</span><br><span class="line">        # included in the NDK.</span><br><span class="line">        $&#123;log-lib&#125;)</span><br><span class="line">···</span><br></pre></td></tr></table></figure>
<ul>
<li><a target="_blank" rel="noopener" href="https://cmake.org/cmake/help/latest/manual/cmake-commands.7.html">CMake 命令详细信息文档</a></li>
</ul>
<h2 id="常用的-Android-NDK-原生-API"><a href="#常用的-Android-NDK-原生-API" class="headerlink" title="常用的 Android NDK 原生 API"></a>常用的 Android NDK 原生 API</h2><table>
<thead>
<tr>
<th>支持 NDK 的 API 级别</th>
<th>关键原生 API</th>
<th>包括</th>
</tr>
</thead>
<tbody><tr>
<td>3</td>
<td>Java 原生接口</td>
<td>#include &lt;jni.h&gt;</td>
</tr>
<tr>
<td>3</td>
<td>Android 日志记录 API</td>
<td>#include &lt;android&#x2F;log.h&gt;</td>
</tr>
<tr>
<td>5</td>
<td>OpenGL ES 2.0</td>
<td>#include &lt;GLES2&#x2F;gl2.h&gt;<br>#include &lt;GLES2&#x2F;gl2ext.h&gt;</td>
</tr>
<tr>
<td>8</td>
<td>Android 位图 API</td>
<td>#include &lt;android&#x2F;bitmap.h&gt;</td>
</tr>
<tr>
<td>9</td>
<td>OpenSL ES</td>
<td>#include &lt;SLES&#x2F;OpenSLES.h&gt;<br>#include &lt;SLES&#x2F;OpenSLES_Platform.h&gt;<br>#include &lt;SLES&#x2F;OpenSLES_Android.h&gt;<br>#include &lt;SLES&#x2F;OpenSLES_AndroidConfiguration.h&gt;</td>
</tr>
<tr>
<td>9</td>
<td>原生应用 API</td>
<td>#include &lt;android&#x2F;rect.h&gt;<br>#include &lt;android&#x2F;window.h&gt;<br>#include&lt;android&#x2F;native_activity.h&gt;<br>···</td>
</tr>
<tr>
<td>18</td>
<td>OpenGL ES 3.0</td>
<td>#include &lt;GLES3&#x2F;gl3.h&gt;<br>#include &lt;GLES3&#x2F;gl3ext.h&gt;</td>
</tr>
<tr>
<td>21</td>
<td>原生媒体 API</td>
<td>#include &lt;media&#x2F;NdkMediaCodec.h&gt;<br>#include &lt;media&#x2F;NdkMediaCrypto.h&gt;<br>···</td>
</tr>
<tr>
<td>24</td>
<td>原生相机 API</td>
<td>#include &lt;camera&#x2F;NdkCameraCaptureSession.h&gt;<br>#include &lt;camera&#x2F;NdkCameraDevice.h&gt;<br>···</td>
</tr>
<tr>
<td>···</td>
<td></td>
<td></td>
</tr>
</tbody></table>
<h1 id="类加载器"><a href="#类加载器" class="headerlink" title="类加载器"></a>类加载器</h1><p><img src="https://img-blog.csdn.net/20161021101447117?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQv/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center"></p>
<h2 id="双亲委托模式"><a href="#双亲委托模式" class="headerlink" title="双亲委托模式"></a>双亲委托模式</h2><p>某个特定的类加载器在接到加载类的请求时，首先将加载任务委托给父类加载器，依次递归，如果父类加载器可以完成类加载任务，就成功返回；只有父类加载器无法完成此加载任务时，才自己去加载。</p>
<p>因为这样可以避免重复加载，当父亲已经加载了该类的时候，就没有必要子 ClassLoader 再加载一次。如果不使用这种委托模式，那我们就可以随时使用自定义的类来动态替代一些核心的类，存在非常大的安全隐患。</p>
<h2 id="DexPathList"><a href="#DexPathList" class="headerlink" title="DexPathList"></a>DexPathList</h2><p>DexClassLoader 重载了 <code>findClass</code> 方法，在加载类时会调用其内部的 DexPathList 去加载。DexPathList 是在构造 DexClassLoader 时生成的，其内部包含了 DexFile。</p>
<p><code>DexPathList.java</code></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line">···</span><br><span class="line"><span class="keyword">public</span> Class <span class="title function_">findClass</span><span class="params">(String name)</span> &#123;</span><br><span class="line">    <span class="keyword">for</span> (Element element : dexElements) &#123;</span><br><span class="line">        <span class="type">DexFile</span> <span class="variable">dex</span> <span class="operator">=</span> element.dexFile;</span><br><span class="line">        <span class="keyword">if</span> (dex != <span class="literal">null</span>) &#123;</span><br><span class="line">            <span class="type">Class</span> <span class="variable">clazz</span> <span class="operator">=</span> dex.loadClassBinaryName(name, definingContext);</span><br><span class="line">            <span class="keyword">if</span> (clazz != <span class="literal">null</span>) &#123;</span><br><span class="line">                <span class="keyword">return</span> clazz;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> <span class="literal">null</span>;</span><br><span class="line">&#125;</span><br><span class="line">···</span><br></pre></td></tr></table></figure>


                
            </div>
            <hr/>

            

    <div class="reprint" id="reprint-statement">
        
            <div class="reprint__author">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-user">
                        文章作者:
                    </i>
                </span>
                <span class="reprint-info">
                    <a href="/hello-world/about" rel="external nofollow noreferrer">Easy Zhang</a>
                </span>
            </div>
            <div class="reprint__type">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-link">
                        文章链接:
                    </i>
                </span>
                <span class="reprint-info">
                    <a href="https://cainiaodashixiong.gitee.io/hello-world/hello-world/2022/11/28/Android%E6%89%A9%E5%B1%95%E7%9F%A5%E8%AF%86%E7%82%B9/">https://cainiaodashixiong.gitee.io/hello-world/hello-world/2022/11/28/Android%E6%89%A9%E5%B1%95%E7%9F%A5%E8%AF%86%E7%82%B9/</a>
                </span>
            </div>
            <div class="reprint__notice">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-copyright">
                        版权声明:
                    </i>
                </span>
                <span class="reprint-info">
                    本博客所有文章除特別声明外，均采用
                    <a href="https://creativecommons.org/licenses/by/4.0/deed.zh" rel="external nofollow noreferrer" target="_blank">CC BY 4.0</a>
                    许可协议。转载请注明来源
                    <a href="/hello-world/about" target="_blank">Easy Zhang</a>
                    !
                </span>
            </div>
        
    </div>

    <script async defer>
      document.addEventListener("copy", function (e) {
        let toastHTML = '<span>复制成功，请遵循本文的转载规则</span><button class="btn-flat toast-action" onclick="navToReprintStatement()" style="font-size: smaller">查看</a>';
        M.toast({html: toastHTML})
      });

      function navToReprintStatement() {
        $("html, body").animate({scrollTop: $("#reprint-statement").offset().top - 80}, 800);
      }
    </script>



            <div class="tag_share" style="display: block;">
                <div class="post-meta__tag-list" style="display: inline-block;">
                    
                        <div class="article-tag">
                            
                                <a href="/hello-world/tags/%E5%AD%A6%E4%B9%A0/">
                                    <span class="chip bg-color">学习</span>
                                </a>
                            
                        </div>
                    
                </div>
                <div class="post_share" style="zoom: 80%; width: fit-content; display: inline-block; float: right; margin: -0.15rem 0;">
                    <link rel="stylesheet" type="text/css" href="/hello-world/libs/share/css/share.min.css">
<div id="article-share">

    
    <div class="social-share" data-sites="twitter,facebook,google,qq,qzone,wechat,weibo,douban,linkedin" data-wechat-qrcode-helper="<p>微信扫一扫即可分享！</p>"></div>
    <script src="/hello-world/libs/share/js/social-share.min.js"></script>
    

    

</div>

                </div>
            </div>
            
                <div id="reward">
    <a href="#rewardModal" class="reward-link modal-trigger btn-floating btn-medium waves-effect waves-light red">赏</a>

    <!-- Modal Structure -->
    <div id="rewardModal" class="modal">
        <div class="modal-content">
            <a class="close modal-close"><i class="fas fa-times"></i></a>
            <h4 class="reward-title">你的赏识是我前进的动力</h4>
            <div class="reward-content">
                <div class="reward-tabs">
                    <ul class="tabs row">
                        <li class="tab col s6 alipay-tab waves-effect waves-light"><a href="#alipay">支付宝</a></li>
                        <li class="tab col s6 wechat-tab waves-effect waves-light"><a href="#wechat">微 信</a></li>
                    </ul>
                    <div id="alipay">
                        <img src="/hello-world/medias/reward/alipay.jpg" class="reward-img" alt="支付宝打赏二维码">
                    </div>
                    <div id="wechat">
                        <img src="/hello-world/medias/reward/wechat.png" class="reward-img" alt="微信打赏二维码">
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
    $(function () {
        $('.tabs').tabs();
    });
</script>

            
        </div>
    </div>

    

    

    

    

    

    

    

    

    

<article id="prenext-posts" class="prev-next articles">
    <div class="row article-row">
        
        <div class="article col s12 m6" data-aos="fade-up">
            <div class="article-badge left-badge text-color">
                <i class="fas fa-chevron-left"></i>&nbsp;上一篇</div>
            <div class="card">
                <a href="/hello-world/2022/11/28/Android%E7%9F%A5%E8%AF%86%E7%82%B9%E6%B1%87%E6%80%BB/">
                    <div class="card-image">
                        
                        
                        <img src="/hello-world/medias/featureimages/3.jpg" class="responsive-img" alt="Android 知识点汇总">
                        
                        <span class="card-title">Android 知识点汇总</span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">
                        
                            
                        
                    </div>
                    <div class="publish-info">
                        <span class="publish-date">
                            <i class="far fa-clock fa-fw icon-date"></i>2022-11-28
                        </span>
                        <span class="publish-author">
                            
                            <i class="fas fa-user fa-fw"></i>
                            Easy Zhang
                            
                        </span>
                    </div>
                </div>
                
                <div class="card-action article-tags">
                    
                    <a href="/hello-world/tags/%E5%AD%A6%E4%B9%A0/">
                        <span class="chip bg-color">学习</span>
                    </a>
                    
                </div>
                
            </div>
        </div>
        
        
        <div class="article col s12 m6" data-aos="fade-up">
            <div class="article-badge right-badge text-color">
                下一篇&nbsp;<i class="fas fa-chevron-right"></i>
            </div>
            <div class="card">
                <a href="/hello-world/2022/11/28/Android%E5%BC%80%E6%BA%90%E5%BA%93%E6%BA%90%E7%A0%81%E5%88%86%E6%9E%90/">
                    <div class="card-image">
                        
                        
                        <img src="/hello-world/medias/featureimages/2.jpg" class="responsive-img" alt="开源库源码分析">
                        
                        <span class="card-title">开源库源码分析</span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">
                        
                            
                        
                    </div>
                    <div class="publish-info">
                            <span class="publish-date">
                                <i class="far fa-clock fa-fw icon-date"></i>2022-11-28
                            </span>
                        <span class="publish-author">
                            
                            <i class="fas fa-user fa-fw"></i>
                            Easy Zhang
                            
                        </span>
                    </div>
                </div>
                
                <div class="card-action article-tags">
                    
                    <a href="/hello-world/tags/%E5%AD%A6%E4%B9%A0/">
                        <span class="chip bg-color">学习</span>
                    </a>
                    
                </div>
                
            </div>
        </div>
        
    </div>
</article>

</div>



<!-- 代码块功能依赖 -->
<script type="text/javascript" src="/hello-world/libs/codeBlock/codeBlockFuction.js"></script>



<!-- 代码语言 -->

<script type="text/javascript" src="/hello-world/libs/codeBlock/codeLang.js"></script>


<!-- 代码块复制 -->

<script type="text/javascript" src="/hello-world/libs/codeBlock/codeCopy.js"></script>


<!-- 代码块收缩 -->

<script type="text/javascript" src="/hello-world/libs/codeBlock/codeShrink.js"></script>



    </div>
    <div id="toc-aside" class="expanded col l3 hide-on-med-and-down">
        <div class="toc-widget card" style="background-color: white;">
            <div class="toc-title"><i class="far fa-list-alt"></i>&nbsp;&nbsp;目录</div>
            <div id="toc-content"></div>
        </div>
    </div>
</div>

<!-- TOC 悬浮按钮. -->

<div id="floating-toc-btn" class="hide-on-med-and-down">
    <a class="btn-floating btn-large bg-color">
        <i class="fas fa-list-ul"></i>
    </a>
</div>


<script src="/hello-world/libs/tocbot/tocbot.min.js"></script>
<script>
    $(function () {
        tocbot.init({
            tocSelector: '#toc-content',
            contentSelector: '#articleContent',
            headingsOffset: -($(window).height() * 0.4 - 45),
            collapseDepth: Number('0'),
            headingSelector: 'h2, h3, h4'
        });

        // Set scroll toc fixed.
        let tocHeight = parseInt($(window).height() * 0.4 - 64);
        let $tocWidget = $('.toc-widget');
        $(window).scroll(function () {
            let scroll = $(window).scrollTop();
            /* add post toc fixed. */
            if (scroll > tocHeight) {
                $tocWidget.addClass('toc-fixed');
            } else {
                $tocWidget.removeClass('toc-fixed');
            }
        });

        
        /* 修复文章卡片 div 的宽度. */
        let fixPostCardWidth = function (srcId, targetId) {
            let srcDiv = $('#' + srcId);
            if (srcDiv.length === 0) {
                return;
            }

            let w = srcDiv.width();
            if (w >= 450) {
                w = w + 21;
            } else if (w >= 350 && w < 450) {
                w = w + 18;
            } else if (w >= 300 && w < 350) {
                w = w + 16;
            } else {
                w = w + 14;
            }
            $('#' + targetId).width(w);
        };

        // 切换TOC目录展开收缩的相关操作.
        const expandedClass = 'expanded';
        let $tocAside = $('#toc-aside');
        let $mainContent = $('#main-content');
        $('#floating-toc-btn .btn-floating').click(function () {
            if ($tocAside.hasClass(expandedClass)) {
                $tocAside.removeClass(expandedClass).hide();
                $mainContent.removeClass('l9');
            } else {
                $tocAside.addClass(expandedClass).show();
                $mainContent.addClass('l9');
            }
            fixPostCardWidth('artDetail', 'prenext-posts');
        });
        
    });
</script>

    

</main>




    <footer class="page-footer bg-color">
    
        <link rel="stylesheet" href="/hello-world/libs/aplayer/APlayer.min.css">
<style>
    .aplayer .aplayer-lrc p {
        
        display: none;
        
        font-size: 12px;
        font-weight: 700;
        line-height: 16px !important;
    }

    .aplayer .aplayer-lrc p.aplayer-lrc-current {
        
        display: none;
        
        font-size: 15px;
        color: #42b983;
    }

    
    .aplayer.aplayer-fixed.aplayer-narrow .aplayer-body {
        left: -66px !important;
    }

    .aplayer.aplayer-fixed.aplayer-narrow .aplayer-body:hover {
        left: 0px !important;
    }

    
</style>
<div class="">
    
    <div class="row">
        <meting-js class="col l8 offset-l2 m10 offset-m1 s12"
                   server="netease"
                   type="playlist"
                   id="503838841"
                   fixed='true'
                   autoplay='false'
                   theme='#42b983'
                   loop='all'
                   order='random'
                   preload='auto'
                   volume='0.7'
                   list-folded='true'
        >
        </meting-js>
    </div>
</div>

<script src="/hello-world/libs/aplayer/APlayer.min.js"></script>
<script src="/hello-world/libs/aplayer/Meting.min.js"></script>

    

    <div class="container row center-align"
         style="margin-bottom: 0px !important;">
        <div class="col s12 m8 l8 copy-right">
            Copyright&nbsp;&copy;
            
                <span id="year">2019-2023</span>
            
            <a href="/hello-world/about" target="_blank">Easy Zhang</a>
            |&nbsp;Powered by&nbsp;<a href="https://hexo.io/" target="_blank">Hexo</a>
            |&nbsp;Theme&nbsp;<a href="https://github.com/blinkfox/hexo-theme-matery" target="_blank">Matery</a>
            <br>
            
            
            
                
            
            
                <span id="busuanzi_container_site_pv">
                &nbsp;|&nbsp;<i class="far fa-eye"></i>&nbsp;总访问量:&nbsp;
                    <span id="busuanzi_value_site_pv" class="white-color"></span>
            </span>
            
            
                <span id="busuanzi_container_site_uv">
                &nbsp;|&nbsp;<i class="fas fa-users"></i>&nbsp;总访问人数:&nbsp;
                    <span id="busuanzi_value_site_uv" class="white-color"></span>
            </span>
            
            <br>

            <!-- 运行天数提醒. -->
            
            <br>
            
        </div>
        <div class="col s12 m4 l4 social-link social-statis">
    <a href="https://gitee.com/CaiNiaoDaShiXiong" class="tooltipped" target="_blank" data-tooltip="访问我的GitHub" data-position="top" data-delay="50">
        <i class="fab fa-github"></i>
    </a>



    <a href="mailto:838489284@qq.com" class="tooltipped" target="_blank" data-tooltip="邮件联系我" data-position="top" data-delay="50">
        <i class="fas fa-envelope-open"></i>
    </a>







    <a href="tencent://AddContact/?fromId=50&fromSubId=1&subcmd=all&uin=838489284" class="tooltipped" target="_blank" data-tooltip="QQ联系我: 838489284" data-position="top" data-delay="50">
        <i class="fab fa-qq"></i>
    </a>







    <a href="/hello-world/atom.xml" class="tooltipped" target="_blank" data-tooltip="RSS 订阅" data-position="top" data-delay="50">
        <i class="fas fa-rss"></i>
    </a>

</div>
    </div>
</footer>

<div class="progress-bar"></div>


    <!-- 搜索遮罩框 -->
<div id="searchModal" class="modal">
    <div class="modal-content">
        <div class="search-header">
            <span class="title"><i class="fas fa-search"></i>&nbsp;&nbsp;搜索</span>
            <input type="search" id="searchInput" name="s" placeholder="请输入搜索的关键字"
                   class="search-input">
        </div>
        <div id="searchResult"></div>
    </div>
</div>

<script type="text/javascript">
$(function () {
    var searchFunc = function (path, search_id, content_id) {
        'use strict';
        $.ajax({
            url: path,
            dataType: "xml",
            success: function (xmlResponse) {
                // get the contents from search data
                var datas = $("entry", xmlResponse).map(function () {
                    return {
                        title: $("title", this).text(),
                        content: $("content", this).text(),
                        url: $("url", this).text()
                    };
                }).get();
                var $input = document.getElementById(search_id);
                var $resultContent = document.getElementById(content_id);
                $input.addEventListener('input', function () {
                    var str = '<ul class=\"search-result-list\">';
                    var keywords = this.value.trim().toLowerCase().split(/[\s\-]+/);
                    $resultContent.innerHTML = "";
                    if (this.value.trim().length <= 0) {
                        return;
                    }
                    // perform local searching
                    datas.forEach(function (data) {
                        var isMatch = true;
                        var data_title = data.title.trim().toLowerCase();
                        var data_content = data.content.trim().replace(/<[^>]+>/g, "").toLowerCase();
                        var data_url = data.url;
                        data_url = data_url.indexOf('/') === 0 ? data.url : '/' + data_url;
                        var index_title = -1;
                        var index_content = -1;
                        var first_occur = -1;
                        // only match artiles with not empty titles and contents
                        if (data_title !== '' && data_content !== '') {
                            keywords.forEach(function (keyword, i) {
                                index_title = data_title.indexOf(keyword);
                                index_content = data_content.indexOf(keyword);
                                if (index_title < 0 && index_content < 0) {
                                    isMatch = false;
                                } else {
                                    if (index_content < 0) {
                                        index_content = 0;
                                    }
                                    if (i === 0) {
                                        first_occur = index_content;
                                    }
                                }
                            });
                        }
                        // show search results
                        if (isMatch) {
                            str += "<li><a href='" + data_url + "' class='search-result-title'>" + data_title + "</a>";
                            var content = data.content.trim().replace(/<[^>]+>/g, "");
                            if (first_occur >= 0) {
                                // cut out 100 characters
                                var start = first_occur - 20;
                                var end = first_occur + 80;
                                if (start < 0) {
                                    start = 0;
                                }
                                if (start === 0) {
                                    end = 100;
                                }
                                if (end > content.length) {
                                    end = content.length;
                                }
                                var match_content = content.substr(start, end);
                                // highlight all keywords
                                keywords.forEach(function (keyword) {
                                    var regS = new RegExp(keyword, "gi");
                                    match_content = match_content.replace(regS, "<em class=\"search-keyword\">" + keyword + "</em>");
                                });

                                str += "<p class=\"search-result\">" + match_content + "...</p>"
                            }
                            str += "</li>";
                        }
                    });
                    str += "</ul>";
                    $resultContent.innerHTML = str;
                });
            }
        });
    };

    searchFunc('/hello-world/search.xml', 'searchInput', 'searchResult');
});
</script>

    <!-- 白天和黑夜主题 -->
<div class="stars-con">
    <div id="stars"></div>
    <div id="stars2"></div>
    <div id="stars3"></div>  
</div>

<script>
    function switchNightMode() {
        $('<div class="Cuteen_DarkSky"><div class="Cuteen_DarkPlanet"></div></div>').appendTo($('body')),
        setTimeout(function () {
            $('body').hasClass('DarkMode') 
            ? ($('body').removeClass('DarkMode'), localStorage.setItem('isDark', '0'), $('#sum-moon-icon').removeClass("fa-sun").addClass('fa-moon')) 
            : ($('body').addClass('DarkMode'), localStorage.setItem('isDark', '1'), $('#sum-moon-icon').addClass("fa-sun").removeClass('fa-moon')),
            
            setTimeout(function () {
            $('.Cuteen_DarkSky').fadeOut(1e3, function () {
                $(this).remove()
            })
            }, 2e3)
        })
    }
</script>

    <!-- 回到顶部按钮 -->
<div id="backTop" class="top-scroll">
    <a class="btn-floating btn-large waves-effect waves-light" href="#!">
        <i class="fas fa-arrow-up"></i>
    </a>
</div>


    <script src="/hello-world/libs/materialize/materialize.min.js"></script>
    <script src="/hello-world/libs/masonry/masonry.pkgd.min.js"></script>
    <script src="/hello-world/libs/aos/aos.js"></script>
    <script src="/hello-world/libs/scrollprogress/scrollProgress.min.js"></script>
    <script src="/hello-world/libs/lightGallery/js/lightgallery-all.min.js"></script>
    <script src="/hello-world/js/matery.js"></script>

    

    

    <!-- 雪花特效 -->
    

    <!-- 鼠标星星特效 -->
     
        <script type="text/javascript">
            // 只在桌面版网页启用特效
            var windowWidth = $(window).width();
            if (windowWidth > 768) {
                document.write('<script type="text/javascript" src="/hello-world/libs/others/star.js"><\/script>');
            }
        </script>
    

     
        <script src="https://ssl.captcha.qq.com/TCaptcha.js"></script>
        <script src="/hello-world/libs/others/TencentCaptcha.js"></script>
        <button id="TencentCaptcha" data-appid="xxxxxxxxxx" data-cbfn="callback" type="button" hidden></button>
    

    <!-- Baidu Analytics -->

    <!-- Baidu Push -->

<script>
    (function () {
        var bp = document.createElement('script');
        var curProtocol = window.location.protocol.split(':')[0];
        if (curProtocol === 'https') {
            bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';
        } else {
            bp.src = 'http://push.zhanzhang.baidu.com/push.js';
        }
        var s = document.getElementsByTagName("script")[0];
        s.parentNode.insertBefore(bp, s);
    })();
</script>

    
    <script src="/hello-world/libs/others/clicklove.js" async="async"></script>
    
    
    <script async src="/hello-world/libs/others/busuanzi.pure.mini.js"></script>
    

    

    

    <!--腾讯兔小巢-->
    
    

    

    

    
    <script src="/hello-world/libs/instantpage/instantpage.js" type="module"></script>
    

</body>

</html>
